if / else in C++
Basic Syntax
The simplest form runs a block only when the condition is true. If you omit the braces, only the single statement immediately following the condition belongs to the if — everything after that runs unconditionally.
#include <iostream>
using namespace std;
int main() {
int age = 20;
if (age >= 18) {
cout << "You are an adult." << endl;
}
return 0;
}if / else
int temperature = 15;
if (temperature > 25) {
cout << "It's warm." << endl;
} else {
cout << "It's cool." << endl;
}if / else if / else
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;
}
// Output: Grade: C{ } around if/else bodies, even for a single statement. Without braces, only the very next statement belongs to the if. This is the source of a classic C++ bug: adding a second line later without noticing it now runs unconditionally.// Dangerous: looks like both lines are guarded, but they are not.
if (age >= 18)
cout << "Adult" << endl;
cout << "Welcome!" << endl; // Runs ALWAYS, regardless of age!
// Safe: braces make the intent explicit and immune to this mistake.
if (age >= 18) {
cout << "Adult" << endl;
cout << "Welcome!" << endl;
}The Ternary (Conditional) Operator
condition ? valueIfTrue : valueIfFalse is a compact alternative to a full if/else. It is an expression, not a statement, so it can be used directly inside another expression, such as an initialization or a function call.int a = 10, b = 20;
// Instead of:
int max;
if (a > b) {
max = a;
} else {
max = b;
}
// Write:
int max2 = (a > b) ? a : b;
cout << "Max: " << max2 << endl; // Output: Max: 20if with an Init-Statement (C++17)
C++17 lets you declare and initialize a variable directly inside the if statement, scoped to the if/else block only. This is very useful when a value is only needed for the check itself, keeping it out of the surrounding scope.
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> ages = { {"Alice", 30}, {"Bob", 25} };
// 'it' only exists within this if/else - not visible afterward.
if (auto it = ages.find("Alice"); it != ages.end()) {
cout << "Found: " << it->second << endl;
} else {
cout << "Not found." << endl;
}
return 0;
}Key Points
Conditions must be convertible to bool; 0 is false, any non-zero value is true.
else if chains are evaluated top-to-bottom; the first true branch runs and the rest are skipped.
Always use braces, even for single-statement bodies, to avoid dangling-else style bugs.
The ternary operator ?: is an expression that yields a value, useful for short conditional assignments.
C++17 if-with-initializer scopes a helper variable to just the if/else statement.