Cppif / else

if / else in C++

Decision-making is at the heart of every non-trivial program. C++ gives you the if, if / else, and if / else if / else statements to run different blocks of code depending on whether a condition evaluates to true or false. In C++, any expression that can be converted to a boolean is a valid condition — zero (or a null pointer) is treated as false, and any non-zero value is treated as true.
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.

CPP
#include <iostream>
using namespace std;

int main() {
    int age = 20;

    if (age >= 18) {
        cout << "You are an adult." << endl;
    }

    return 0;
}
if / else
Add an else branch to run alternate code when the condition is false.

CPP
int temperature = 15;

if (temperature > 25) {
    cout << "It's warm." << endl;
} else {
    cout << "It's cool." << endl;
}
if / else if / else
Chain multiple conditions with else if when there are more than two possible outcomes. Conditions are tested in order, top to bottom, and the first one that is true wins — the rest are skipped.

CPP
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
Warning
Always use braces { } 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.

CPP
// 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
For simple two-way choices that produce a value, the ternary 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.

CPP
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: 20
Tip
Keep ternary expressions short and readable. If the true/false branches are complex, a regular if/else is usually clearer — don't nest ternaries inside ternaries.
if 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.

CPP
#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;
}
Note
The init-statement form is equivalent to wrapping the whole if/else in an extra pair of braces and declaring the variable just before it — C++17 simply makes that pattern built-in syntax, avoiding variable leakage into the enclosing scope.
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.