So far, every program we have written runs from top to bottom, executing every statement exactly once. Real programs are not like that. An ATM gives you money only if your balance is enough. A result portal prints "Pass" only if your marks are at least 40. A login screen opens your account only if the password matches.
Choosing between different paths based on a condition is called decision making, and in C++ the main tool for it is the if statement and its relatives. In this chapter we will learn all forms of if, how C++ decides whether a condition is "true", the C++17 if with initializer, the famous dangling else problem, and the mistakes that show up again and again in exams and interviews.
What is a Conditional Statement?
A conditional statement executes a statement (or a block of statements) only when a given condition is true, and optionally executes a different block when it is false.
C++ gives us these forms:
| Form | Use it when |
|---|---|
if | Do something only when a condition is true |
if-else | Choose between exactly two paths |
else if ladder | Choose one path out of many, checked in order |
Nested if | A decision depends on an earlier decision |
switch | Choose based on the exact value of an integer, char or enum (next chapter, Switch Statement) |
?: operator | Choose between two values inside an expression (seen in Operators) |
The if Statement
The simplest form is:
if (condition) {
// runs only when condition is true
}
The condition must be inside parentheses. If it is true, the block runs; if it is false, the block is skipped and execution continues after the closing brace.
condition?
┌──────┴──────┐
true false
│ │
run the if-block │ (block skipped)
│ │
└──────┬──────┘
│
next statement
#include <iostream>
int main() {
int age = 19;
if (age >= 18) {
std::cout << "You can vote.\n";
}
std::cout << "Program finished.\n";
return 0;
}
Output:
You can vote.
Program finished.
If we change age to 15, only Program finished. is printed. The last line is outside the if, so it always runs.
Braces Are Optional, But Only for One Statement
If the body is a single statement, the braces can be omitted:
if (age >= 18)
std::cout << "You can vote.\n";
But without braces, only the very next statement belongs to the if. Indentation means nothing to the compiler. We will see a nasty bug caused by this in the Common Mistakes section. Many style guides (and most companies) require braces always; it is a good habit.
How C++ Decides "True" or "False"
The condition of an if is contextually converted to bool. That means it does not have to be a comparison. Any value of arithmetic type (and, later, pointers) can be used:
| Value | Treated as |
|---|---|
0, 0.0, '\0', false | false |
Any non-zero number, e.g. 1, -1, 0.5, 'A' | true |
A null pointer (nullptr) | false (see Pointers) |
So if (count) means exactly if (count != 0), and if (!count) means if (count == 0). Both styles are common in real code, so you must be able to read them.
Remember from Operators that relational and logical operators produce a bool, and that && and || short-circuit. Short-circuiting is often used to guard a dangerous check:
if (d != 0 && n / d > 2) { // n / d is evaluated only when d != 0
// ...
}
If d is zero, the left side is false, the right side is never evaluated, and the division by zero (which would be undefined behavior) never happens. Swapping the two sides would break this protection.
The if-else Statement
When there are two alternatives, add an else block. Exactly one of the two blocks runs, never both and never neither.
#include <iostream>
int main() {
int n = 17;
if (n % 2 == 0) {
std::cout << n << " is even\n";
} else {
std::cout << n << " is odd\n";
}
return 0;
}
Output:
17 is odd
For negative numbers this test still works: -7 % 2 is -1 (the sign follows the left operand, as we saw in Operators), which is not 0, so -7 is correctly reported as odd. A test like n % 2 == 1, on the other hand, would wrongly call -7 "not odd". Prefer n % 2 != 0 or n % 2 == 0.
The else-if Ladder
When there are more than two possibilities, we chain conditions with else if. C++ checks the conditions from top to bottom and runs the block of the first condition that is true. All the remaining conditions are skipped. The final else (optional) runs when none of the conditions is true.
#include <iostream>
int main() {
int marks;
std::cout << "Enter marks (0-100): ";
std::cin >> marks;
if (marks < 0 || marks > 100) {
std::cout << "Invalid marks\n";
} else if (marks >= 90) {
std::cout << "Grade: O (Outstanding)\n";
} else if (marks >= 75) {
std::cout << "Grade: A\n";
} else if (marks >= 60) {
std::cout << "Grade: B\n";
} else if (marks >= 40) {
std::cout << "Grade: C\n";
} else {
std::cout << "Grade: F (Fail)\n";
}
return 0;
}
If the user enters 78:
Enter marks (0-100): 78
Grade: A
Let's trace it step by step for 78:
marks < 0 || marks > 100 ? 78 < 0 false, 78 > 100 false → false, go on
marks >= 90 ? false, go on
marks >= 75 ? true → print "Grade: A", skip the rest
Notice why the order matters. The condition marks >= 75 does not need to say && marks < 90, because we only reach it when marks >= 90 was already false. If we had written the conditions in the opposite order (>= 40 first), a student with 95 would get grade C, because 95 >= 40 is true and the ladder stops there.
In an else-if ladder, at most one block runs: the first one whose condition is true. Put the most specific (or most restrictive) conditions first.
Also notice that the invalid-input check comes first. Validating input before using it is a good habit.
else if Is Not a Special Keyword
C++ has no elseif keyword. An else if is simply an else whose single statement happens to be another if. These two are identical:
if (a) {
x = 1;
} else if (b) {
x = 2;
} else {
x = 3;
}
if (a) {
x = 1;
} else {
if (b) {
x = 2;
} else {
x = 3;
}
}
The first layout is preferred because it stays flat no matter how many cases you add.
Nested if Statements
An if can be placed inside another if or else. This is useful when a second decision makes sense only after the first one. A classic exam program: the largest of three numbers.
#include <iostream>
int main() {
int a = 12, b = 45, c = 30;
if (a >= b) {
if (a >= c) {
std::cout << "Largest: " << a << '\n';
} else {
std::cout << "Largest: " << c << '\n';
}
} else {
if (b >= c) {
std::cout << "Largest: " << b << '\n';
} else {
std::cout << "Largest: " << c << '\n';
}
}
return 0;
}
Output:
Largest: 45
Trace: a >= b is 12 >= 45, false, so we go to the outer else. There b >= c is 45 >= 30, true, so 45 is printed. Exactly two comparisons are made, whatever the values. (Using >= instead of > makes the program correct when two values are equal.)
The same logic can be written as a flat ladder with &&:
if (a >= b && a >= c) largest = a;
else if (b >= c) largest = b; // here we know a is not the largest
else largest = c;
In real code you would simply write std::max({a, b, c}) from <algorithm>, but exams love the nested version. Deep nesting (three or more levels) makes code hard to read; flatten it with && or else if when you can.
The Dangling else Problem
What happens when an if without braces contains another if, followed by one else? Which if does the else belong to?
Rule: an
elsealways belongs to the nearest precedingifin the same block that does not already have anelse.
Indentation does not change this rule. Look at this program:
#include <iostream>
int main() {
int x = 5, y = -3;
if (x > 0)
if (y > 0)
std::cout << "both positive\n";
else
std::cout << "x is not positive\n"; // misleading indentation!
std::cout << "done\n";
return 0;
}
Output:
x is not positive
done
The programmer meant the else to pair with if (x > 0), but it actually pairs with the inner if (y > 0). Since x is positive and y is not, the inner else runs and prints a message that is plainly wrong. GCC notices the suspicious layout:
warning: suggest explicit braces to avoid ambiguous ‘else’ [-Wdangling-else]
The fix is to use braces, which make the pairing explicit:
if (x > 0) {
if (y > 0)
std::cout << "both positive\n";
} else {
std::cout << "x is not positive\n";
}
Now the inner if is closed inside the braces, so the else can only belong to the outer if. With x = 5, y = -3, nothing is printed except done.
Worked Example: Leap Year
A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap years only if they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 is not.
The rule can be written as a single condition:
#include <iostream>
int main() {
int year = 1900;
bool leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (leap) {
std::cout << year << " is a leap year\n";
} else {
std::cout << year << " is not a leap year\n";
}
return 0;
}
Output:
1900 is not a leap year
Or as an else-if ladder, where the order of the checks does the work. The most specific rule (400) must come first:
if (year % 400 == 0) leap = true; // 2000
else if (year % 100 == 0) leap = false; // 1900
else if (year % 4 == 0) leap = true; // 2024
else leap = false; // 2026
Storing a complicated condition in a well-named bool variable such as leap is a simple trick that makes code much easier to read.
Worked Example: Roots of a Quadratic Equation
For ax² + bx + c = 0, the discriminant D = b² − 4ac decides the kind of roots. This is a natural three-way decision:
#include <iostream>
#include <cmath>
int main() {
double a = 1, b = -5, c = 6;
if (a == 0) {
std::cout << "Not a quadratic equation\n";
} else {
double d = b * b - 4 * a * c;
if (d > 0) {
double r1 = (-b + std::sqrt(d)) / (2 * a);
double r2 = (-b - std::sqrt(d)) / (2 * a);
std::cout << "Real and distinct: " << r1 << ", " << r2 << '\n';
} else if (d == 0) {
std::cout << "Real and equal: " << -b / (2 * a) << '\n';
} else {
double re = -b / (2 * a);
double im = std::sqrt(-d) / (2 * a);
std::cout << "Complex: " << re << " ± " << im << "i\n";
}
}
return 0;
}
Output:
Real and distinct: 3, 2
Notice two things. First, the variable d is declared inside the else block, so it exists only there; we will talk about this scoping next. Second, d == 0 compares a double exactly. Here the inputs are small whole numbers, so the arithmetic is exact, but with general floating-point input an exact comparison can fail (see Common Mistakes).
Scope: Variables Declared Inside an if
A pair of braces creates a new block scope. A variable declared inside the if block or the else block is created when execution enters that block and destroyed when it leaves. It cannot be used outside.
if (marks >= 40) {
int bonus = 5;
marks += bonus;
}
// std::cout << bonus; // error: 'bonus' was not declared in this scope
Keeping variables in the smallest possible scope is good practice: they can't be misused elsewhere, and the reader knows exactly where they matter.
if with Initializer (C++17)
Very often, we compute a value only to test it, and we don't need it afterwards. Since C++17, an if can contain an init-statement before the condition, separated by a semicolon:
if (init-statement; condition) {
...
} else {
...
}
The variable declared in the init-statement is visible in the condition, in the if block and in the else block(s), but not after the whole statement.
#include <iostream>
int main() {
int stock = 0;
if (int remaining = stock - 1; remaining >= 0) { // C++17
std::cout << "Sold! " << remaining << " left\n";
} else {
std::cout << "Out of stock (would be " << remaining << ")\n";
}
// 'remaining' does not exist here
return 0;
}
Output:
Out of stock (would be -1)
This feature becomes really handy later with containers, for example if (auto it = m.find(key); it != m.end()) in the set & map chapter. The same init-statement is also allowed in switch (next chapter).
if-else vs the Conditional Operator ?:
In Operators we met condition ? a : b. When both branches simply produce a value, the ternary operator is shorter:
// if-else version
int fee;
if (age < 12) {
fee = 50;
} else {
fee = 100;
}
// ternary version: one line, and fee can even be const
const int fee2 = (age < 12) ? 50 : 100;
if-else | ?: | |
|---|---|---|
| What it is | A statement | An expression (has a value) |
| Branches can contain | Any statements, loops, declarations | Only expressions |
Can initialise a const variable | No | Yes |
| Readability with many cases | Good (else-if ladder) | Poor when nested |
Use ?: for small "pick one of two values" situations and if-else for everything else. Avoid deeply nested ternaries like a ? b : c ? d : e ? f : g; they are legal but hard to read.
Newer Forms of if (For Later)
Modern C++ added a few special variants. You don't need them yet, but you should recognise them:
| Syntax | Standard | Meaning |
|---|---|---|
if (init; cond) | C++17 | if with initializer (shown above) |
if constexpr (cond) | C++17 | Condition is checked at compile time; the discarded branch is not instantiated. Mainly used inside templates (see Templates). |
if (cond) [[likely]] { ... } | C++20 | A hint to the compiler that this branch is the common one, for optimisation. It never changes the program's meaning. |
if consteval { ... } | C++23 | Runs the first block when the function is being evaluated at compile time, the else block otherwise. Advanced, used in constexpr functions. |
Common Mistakes
1. Using = Instead of ==
#include <iostream>
int main() {
int x = 0;
if (x = 5) { // assignment, not comparison!
std::cout << "x is 5? x = " << x << '\n';
}
return 0;
}
Output:
x is 5? x = 5
x = 5 stores 5 in x, and the value of the assignment expression is 5, which is non-zero, so the condition is always true. The original value of x is lost. With -Wall, GCC warns:
warning: suggest parentheses around assignment used as truth value [-Wparentheses]
Never ignore this warning. (If you really mean to assign and test, write extra parentheses: if ((x = f())), or better, use the C++17 if-with-initializer.)
2. A Stray Semicolon After the Condition
#include <iostream>
int main() {
int balance = 100;
if (balance > 500); // the ; is an empty statement
{
std::cout << "Premium customer\n";
}
return 0;
}
Output:
Premium customer
The semicolon is an empty statement, and that empty statement is the entire body of the if. The block after it is just an ordinary block that always runs. GCC warns: suggest braces around empty body in an ‘if’ statement [-Wempty-body]. If the if had an else, the code would not even compile, because the else would have no if to attach to.
3. Forgetting Braces Around Two Statements
#include <iostream>
int main() {
int temp = 36;
if (temp > 37)
std::cout << "Fever\n";
std::cout << "Take medicine\n"; // NOT part of the if!
return 0;
}
Output:
Take medicine
Only the first statement belongs to the if. The second one is indented to look like it belongs, but it always runs. GCC's -Wmisleading-indentation (part of -Wall) warns: this ‘if’ clause does not guard.... Always using braces prevents this bug entirely.
4. Comparing Floating-Point Numbers with ==
#include <iostream>
#include <cmath>
int main() {
double sum = 0.1 + 0.2;
if (sum == 0.3)
std::cout << "equal\n";
else
std::cout << "not equal\n";
if (std::fabs(sum - 0.3) < 1e-9)
std::cout << "close enough\n";
return 0;
}
Output:
not equal
close enough
0.1, 0.2 and 0.3 cannot be stored exactly in binary, so 0.1 + 0.2 is 0.30000000000000004..., which is not the same double as 0.3. Compare floating-point values with a tolerance (an epsilon) instead of ==. A fixed tolerance like 1e-9 is fine for values of ordinary size; for very large or very small numbers a relative tolerance is better.
5. Writing a Range Check Like in Maths
if (0 < x < 10) compiles, but it means (0 < x) < 10. The left part is a bool (0 or 1), which is always less than 10, so the condition is always true. Write if (0 < x && x < 10). GCC warns: comparisons like ‘X<=Y<=Z’ do not have their mathematical meaning.
6. Comparing Signed and Unsigned Values
As we saw in Type Conversion & Casting, in if (-1 < 1u) the -1 is converted to a huge unsigned number, so the condition is false. This often bites when comparing an int with a .size() value. Watch for -Wsign-compare warnings.
7. Wrong Order in an else-if Ladder
if (marks >= 40) grade = 'C'; // 95 stops here!
else if (marks >= 75) grade = 'A'; // can never be reached
The second condition can only be checked when marks < 40, so it is never true. Order conditions from the most restrictive to the least restrictive.
Interview / GATE Questions
What is the output? int x = 0; if (x = 0) cout << "A"; else cout << "B";
B. x = 0 is an assignment whose value is 0, which is false, so the else branch runs. (If it were x = 1 the output would be A.)
What is the output? int a = 2; if (a > 5); cout << "big";
big. The semicolon after the condition is the (empty) body of the if, so the output statement always runs.
In if (a) if (b) s1; else s2;, when does s2 run?
When a is true and b is false. The else belongs to the nearest unmatched if, which is if (b). If a is false, neither s1 nor s2 runs. This is the dangling-else rule.
Is if (n % 2 == 1) a correct test for odd numbers in C++?
Only for non-negative n. Since C++11, integer division truncates toward zero, so -3 % 2 is -1, and the test says -3 is not odd. Use n % 2 != 0.
What is the maximum number of conditions evaluated by an else-if ladder with n conditions? When is that maximum reached?
n (ignoring the extra operands inside each condition). It happens when the matching condition is the last one, or when none matches and the final else runs. This is why frequently true cases should come early when the ladder is on a hot path, and why a switch on dense integer values can be faster (the compiler may use a jump table, see the next chapter).
Why is if (p != nullptr && p->value > 0) safe but if (p->value > 0 && p != nullptr) not?
&& evaluates left to right and short-circuits. In the first version, if p is null the left side is false and p->value is never evaluated. In the second version p is dereferenced before the check, which is undefined behavior when p is null.
What is the scope of a variable declared in a C++17 if-initializer?
It is visible in the condition, the if branch and every else/else if branch of that statement, and it is destroyed at the end of the whole if statement.
In Simple Words
iflets a program choose. The condition is converted tobool(zero is false, anything else is true), exactly one branch of an if-else runs, and in a ladder the first true condition wins.
if (c) { ... } → run only when c is true
if (c) { ... } else { ... } → exactly one of two blocks runs
if / else if / else → first true condition wins; order matters
else pairs with nearest unmatched if → use braces to avoid dangling else
if (init; c) (C++17) → variable lives only inside the if/else
= vs ==, stray ;, missing braces → the classic bugs
floating point → compare with a tolerance, not ==
When you need to compare one value against a list of fixed constants, an else-if ladder becomes repetitive. The next chapter, Switch Statement, shows a cleaner tool for exactly that situation.