C++ If…Else
Every useful program needs to make decisions. Should this line execute, or that one? Is the user old enough, did the login succeed, is the number positive or negative? In C++, the if, else if, and else statements are the primary tools for branching your program’s logic based on conditions. Mastering them is the first real step toward writing programs that react intelligently to data.
Overview / How It Works
An if statement evaluates a condition — an expression that results in a boolean value (true or false) — and executes a block of code only if that condition is true. If it’s false, the block is skipped entirely.
Internally, the compiler translates an if statement into a conditional jump instruction at the machine-code level. The CPU evaluates the condition, sets flags in a status register (such as a zero flag or sign flag), and then a conditional branch instruction (like JE, JNE, or JG on x86) decides whether to jump over the block or fall through into it. This is why conditionals are cheap in terms of memory — there’s no extra data allocated — but they do introduce a branch, which modern CPUs try to predict ahead of time using branch prediction. A poorly predictable branch (one that flips between true and false unpredictably in a hot loop) can slow a program down due to pipeline flushes, but for the vast majority of code, this is not something you need to worry about.
In C++, any nonzero numeric value is treated as true, and zero is treated as false. This means you can write if (x) instead of if (x != 0), though writing the explicit comparison is often clearer. Conditions are typically built using relational operators (==, !=, <, >, <=, >=) and logical operators (&&, ||, !).
else if lets you chain multiple conditions together, and else provides a fallback branch that runs only when none of the preceding conditions were true. Only one branch in an if/else-if/else chain ever executes — as soon as a condition matches, C++ skips the rest of the chain.
Syntax
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition1 is false and condition2 is true
} else {
// runs if none of the above conditions are true
}
condition1,condition2— expressions that evaluate totrueorfalse(or a numeric type, where 0 means false).else ifis optional and can be repeated as many times as needed.elseis optional and, if present, must come last.- Curly braces
{ }are optional if a branch contains exactly one statement, but omitting them is a common source of bugs (see Common Mistakes).
Examples
Example 1: A Simple If…Else
#include <iostream>
using namespace std;
int main() {
int age = 20;
if (age >= 18) {
cout << "You are an adult." << endl;
} else {
cout << "You are a minor." << endl;
}
return 0;
}
Output:
You are an adult.
The condition age >= 18 evaluates to true since age is 20, so the first block runs and the else block is skipped.
Example 2: Chaining with Else If
#include <iostream>
using namespace std;
int main() {
int score = 72;
if (score >= 90) {
cout << "Grade: A" << endl;
} else if (score >= 80) {
cout << "Grade: B" << endl;
} else if (score >= 70) {
cout << "Grade: C" << endl;
} else {
cout << "Grade: F" << endl;
}
return 0;
}
Output:
Grade: C
C++ checks each condition top to bottom. score >= 90 is false, score >= 80 is false, but score >= 70 is true, so "Grade: C" prints and the chain stops there — the remaining else is never evaluated.
Example 3: Nested If and Logical Operators
#include <iostream>
using namespace std;
int main() {
int age = 25;
bool hasLicense = true;
if (age >= 18) {
if (hasLicense) {
cout << "You may drive." << endl;
} else {
cout << "You need a license first." << endl;
}
} else {
cout << "Too young to drive." << endl;
}
if (age >= 18 && hasLicense) {
cout << "Equivalent check using &&." << endl;
}
return 0;
}
Output:
You may drive.
Equivalent check using &&.
This demonstrates nesting — an if inside another if — to check multiple related conditions, and shows that combining conditions with && (logical AND) often expresses the same logic more concisely than nesting.
How It Works Step by Step
- The program reaches the
ifstatement and evaluatescondition1. - If
condition1istrue, its block executes, and every otherelse if/elsebranch in the chain is skipped — control jumps to the code after the whole chain. - If
condition1isfalse, the program moves to the nextelse if(if any) and evaluates its condition, repeating the same logic. - If none of the conditions are
trueand anelseblock exists, that block runs. - If none are true and there is no
else, nothing in the chain executes, and the program simply continues after it.
Common Mistakes
Mistake 1: Using assignment (=) instead of comparison (==).
int x = 5;
if (x = 10) { // assigns 10 to x, then evaluates to true (nonzero)
cout << "This always runs!" << endl;
}
This compiles because x = 10 is a valid expression that evaluates to 10, which is treated as true. It silently overwrites x and always enters the block. The fix is to use == for comparison:
int x = 5;
if (x == 10) {
cout << "x is 10" << endl;
}
Mistake 2: Forgetting braces on multi-statement blocks.
int age = 15;
if (age >= 18)
cout << "Adult" << endl;
cout << "Can vote" << endl; // NOT part of the if!
Without braces, only the single statement immediately after if is conditional. The second cout line always runs regardless of age, which is misleading given the indentation. Always wrap multi-statement (and arguably all) blocks in braces:
int age = 15;
if (age >= 18) {
cout << "Adult" << endl;
cout << "Can vote" << endl;
}
Best Practices
- Always use braces
{ }aroundif/elsebodies, even for single statements, to prevent logic errors when code is later edited. - Order
else ifconditions from most specific to least specific, especially with range checks (as in the grading example), since C++ stops at the first match. - Prefer
==comparisons intentionally and consider putting the constant on the left (10 == x) if you want a typo like=to cause a compile error instead of a silent bug. - Combine simple related conditions with
&&and||instead of deeply nestingifstatements, which improves readability. - Keep conditions simple and readable; if a condition becomes very complex, consider storing intermediate results in well-named boolean variables.
- Remember that C++ evaluates
&&and||with short-circuiting — the second operand isn’t evaluated if the first already determines the result — which is useful for guarding against invalid access, e.g.if (ptr != nullptr && ptr->value > 0).
Practice Exercises
- Write a program that reads an integer and prints whether it is “positive”, “negative”, or “zero”.
- Write a program that takes three integers and prints the largest of the three using nested
if/elseor chainedelse ifstatements. - Write a program that reads a year and determines whether it is a leap year (divisible by 4, but not by 100 unless also divisible by 400), printing “Leap year” or “Not a leap year”.
Summary
ifexecutes a block only when its condition istrue;elseprovides a fallback when it’sfalse.else iflets you chain multiple conditions, and only the first matching branch runs.- Conditions are boolean expressions; any nonzero value is treated as
trueand zero asfalse. - Always use braces to avoid accidentally excluding statements from a conditional block.
- Use
==, not=, when comparing values inside a condition. - Combine conditions with
&&/||for cleaner logic instead of deep nesting.
