C++ if Statement
Introduction to if Statements
The if
statement is the simplest conditional control structure in C++. It lets you run specific code only when a given condition evaluates to true.
This is essential for implementing decision-making logic in your programs.
Basic Syntax
if (condition) {
// code executes if condition is true
}
Practical Example
#include <iostream>
using namespace std;
int main() {
int age = 20;
if (age >= 18) {
cout << "You are an adult";
}
return 0;
}
You are an adult
Single Statement if
If the body of the if
contains only one statement, the braces can be omitted:
if (age >= 18)
cout << "You are an adult";
// Equivalent to:
if (age >= 18) {
cout << "You are an adult";
}
If with Initializer (C++17)
Since C++17, you can initialize a variable as part of the if
. The variable’s scope is limited to the if
/else
statement.
#include <iostream>
using namespace std;
int getAge() { return 19; }
int main() {
if (int age = getAge(); age >= 18) {
cout << "Adult: " << age << "\n";
} else {
cout << "Minor: " << age << "\n"; // 'age' is still in scope here
}
// cout << age; // Error: 'age' not in scope outside the if/else
}
Common Pitfalls
- Assignment vs comparison: if (x = 0)
assigns 0 and tests false; use ==
for comparison. Many teams prefer if (0 == x)
to catch accidental assignment.
- Stray semicolon: if (cond); { ... }
ends the if
prematurely and the block always executes.
- Side effects in conditions: Avoid complex function calls with side effects inside the condition.
- Dangling else: else
binds to the nearest unmatched if
; use braces to make intent explicit.
// Bad: assignment instead of comparison
// if (x = 0) { ... } // always false
// Bad: stray semicolon
// if (ready); { start(); } // start() always runs
// Good: explicit and safe
if (x == 0) {
// ...
}