C++ if, else if and else

Make decisions with comparisons, if, else if, else, logical operators, the ternary operator and switch.

Lesson 5 of 44Beginner18 min read

Real programs react to what happens: a game checks whether you've run out of lives, a thermostat checks the temperature, a login screen checks the password. In C++, if statements let your code choose what to do based on a condition.

A condition is an expression that is either true or false, usually a comparison such as score > 100. If the condition is true, the block of code that follows runs. If not, C++ can try other conditions with else if, or fall back to else.

In this lesson you'll write conditions, combine them with logical operators, use the one-line ternary operator, and choose between many fixed values with switch.

Comparisons

OperatorMeaningExample
==equal tolives == 0
!=not equal tochoice != 'q'
> <greater / less thantemp > 30
>= <=greater or equal / less or equalage >= 18

Each comparison gives a bool. You can compare std::string values with == too: if (password == "open123") compares the text.

if, else if, else

C++
int temp = 12;

if (temp >= 25) {
    cout << "Shorts weather" << endl;
} else if (temp >= 10) {
    cout << "Bring a jumper" << endl;
} else {
    cout << "Coat and scarf" << endl;
}
  • The condition goes in round brackets; the code to run goes in curly braces.
  • Only the first branch whose condition is true runs; the rest are skipped.
  • else has no condition and handles everything left over.

Logical operators and the ternary

  • && (and): both sides must be true.
  • || (or): at least one side must be true.
  • ! (not): flips true and false.
C++
if (hasKey && !doorLocked) { ... }

The ternary operator picks one of two values in a single expression: condition ? valueIfTrue : valueIfFalse.

C++
string label = (score >= 50) ? "Pass" : "Fail";

switch

switch compares one integer or character value against a list of case labels:

C++
switch (option) {
    case 1:
        cout << "Start";
        break;
    case 2:
        cout << "Settings";
        break;
    default:
        cout << "Unknown";
}

Every case should end with break. Without it, C++ "falls through" and keeps running the next case's code too. default runs when no case matches. switch doesn't work with std::string; use if chains for text.

Short-circuit evaluation and if with an initialiser

&& and || stop as soon as they know the answer. If the left side of && is false, the whole condition must be false, so the right side is never evaluated. If the left side of || is true, the right side is skipped. This is called short-circuit evaluation, and it lets you put a safety check first:

C++
if (i < scores.size() && scores[i] > 50) { ... }

When i is too big, scores[i] is never read, so there's no out-of-range access. Swap the two sides and the program reads past the end before the check runs. Put cheap or protective tests on the left.

C++ also treats numbers as conditions. Zero counts as false and any other value, including negative numbers, counts as true, which is why if (lives) means "if lives isn't zero". It's legal, but if (lives > 0) says what you mean.

Since C++17, an if can declare a variable just for itself, before a semicolon:

C++
if (int left = total % boxSize; left != 0) {
    cout << left << " items won't fit" << endl;
}

left exists inside the if and its else branches, and disappears afterwards, so it can't be misused later. switch accepts the same form.

C++ if else Syntax

if / else and switch

if (condition) {
    // ...
} else if (other) {
    // ...
} else {
    // ...
}

switch (value) {
    case 1:
        // ...
        break;
    default:
        // ...
}

C++ if else Summary

  • Comparisons produce bool values: true or false.
  • if (condition) { } runs its block only when the condition is true.
  • else if adds more checks; else handles the rest. Only one branch runs.
  • Combine conditions with &&, || and !; pick between two values with ? :.
  • switch matches one int or char against cases; end each case with break.

C++ if else Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Grade from a score

C++
#include <iostream>
using namespace std;

int main() {
    int score = 68;
    char grade;

    if (score >= 80) {
        grade = 'A';
    } else if (score >= 65) {
        grade = 'B';
    } else if (score >= 50) {
        grade = 'C';
    } else {
        grade = 'F';
    }

    cout << "Score " << score << " gets grade " << grade << endl;
    return 0;
}
Output
Score 68 gets grade B
Line-by-line explanation
  1. Line 868 isn't 80 or more, so C++ moves on.
  2. Line 1068 is 65 or more, so grade becomes 'B' and the chain ends.
Example 2

Logical operators

C++
#include <iostream>
using namespace std;

int main() {
    int age = 14;
    bool withAdult = true;

    if (age >= 16 || withAdult) {
        cout << "You can watch the film." << endl;
    }

    bool isTeen = age >= 13 && age <= 19;
    cout << (isTeen ? "Teen ticket" : "Standard ticket") << endl;
    return 0;
}
Output
You can watch the film.
Teen ticket
Line-by-line explanation
  1. Line 8age isn't 16 or more, but withAdult is true, and || needs only one.
  2. Line 12A bool can store the result of a combined condition.
  3. Line 13The ternary chooses which text to print.
Example 3

A simple calculator with switch

C++
#include <iostream>
using namespace std;

int main() {
    double a = 12, b = 4;
    char op = '/';

    switch (op) {
        case '+': cout << a + b << endl; break;
        case '-': cout << a - b << endl; break;
        case '*': cout << a * b << endl; break;
        case '/':
            if (b != 0) cout << a / b << endl;
            else cout << "Can't divide by zero" << endl;
            break;
        default:
            cout << "Unknown operator" << endl;
    }
    return 0;
}
Output
3
Line-by-line explanation
  1. Line 8switch jumps to the case matching op, which is '/'.
  2. Lines 12 to 15Inside a case you can use normal if statements.
  3. Line 15break stops C++ from running the default case as well.

Common C++ if else Mistakes

Assigning instead of comparing

Don't
if (lives = 0) {
    cout << "Game over";
}
Do
if (lives == 0) {
    cout << "Game over";
}

The first version sets lives to 0 and never prints, because 0 counts as false.

Forgetting break in a switch

Don't
switch (n) {
    case 1: cout << "one ";
    case 2: cout << "two ";
}
Do
switch (n) {
    case 1: cout << "one "; break;
    case 2: cout << "two "; break;
}

With n equal to 1, the first version prints "one two" because it falls through.

Chaining comparisons like maths

Don't
if (1 < x < 10) { ... }
Do
if (x > 1 && x < 10) { ... }

C++ works out 1 < x first (true or false, which is 1 or 0) and then compares that with 10, so the first version is almost always true.

C++ if else in Real Projects

Conditions in C++ software

A game engine checks if (player.health <= 0) every frame, a microwave's firmware checks if (doorOpen) stopHeating();, and a compiler itself is full of switch statements that decide what to do with each kind of token in your code.

C++ if else FAQ

How do I compare two strings ignoring case in C++?

The standard library has no single function for it. Make lower-case copies of both strings by looping over the characters with tolower from <cctype>, then compare the copies with ==. Keep this to plain English letters; tolower works on single bytes and doesn't handle accented characters in UTF-8 text.

How do I make several case labels run the same code?

Stack the labels with no code between them: case 'y': case 'Y': cout << "Yes"; break;. Either value jumps to the same statements. If you deliberately let one case's code run on into the next, mark it with [[fallthrough]]; (C++17) so readers and the compiler know it isn't a missing break.

Why do I get "jump to case label" when I declare a variable in a switch?

All the cases share one block, so jumping to a later case would skip the line that creates and initialises the variable, and g++ refuses to compile it. Put braces around the code for that case, as in case 1: { int x = 5; ...; break; }, so the variable only exists inside its own block.

Do I need curly braces around a one-line if in C++?

No: if (done) cout << "Bye"; is legal. But if you later add a second indented line, only the first one belongs to the if, and the second always runs, a classic bug. Most style guides recommend braces every time; g++ -Wall warns when indentation suggests a line is guarded when it isn't.

What is the difference between & and && in C++?

&& is logical AND: it works with true/false values and skips the right side when the left side is false. A single & is bitwise AND, which combines the bits of two numbers and always evaluates both sides. Use && in conditions; a single & there usually means a typo.

C++ if else Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code so it prints "Freezing" when temp is 0 or below.

int temp = -3;
 (temp  0) {
    cout << "Freezing";
}
Predict the outputeasy

What does this print?

int x = 4;
if (x > 5) cout << "A";
else if (x > 3) cout << "B";
else cout << "C";
Predict the outputmedium

What does this print?

int n = 2;
switch (n) {
    case 1: cout << "one ";
    case 2: cout << "two ";
    case 3: cout << "three ";
}
Multiple choicemedium

Which condition is true when x is between 1 and 10, exclusive?

Predict the outputmedium

What does this print?

int n = 7;
cout << (n % 2 == 0 ? "even" : "odd") << endl;

C++ if else Quiz

5 questions to check what you learned.

  1. What does ! do?

    • Reverses a boolean value
    • Ends a statement
    • Compares two values
    • Marks a comment
  2. What happens if a switch case has no break?

    • The program crashes
    • The compiler reports an error
    • Execution continues into the next case
    • The switch restarts
  3. Which value does (10 > 3) ? "yes" : "no" produce?

    • "no"
    • true
    • 1
    • "yes"
  4. Can switch be used directly with a std::string?

    • Yes, always
    • No, it only works with whole-number types like int and char
    • Only with short strings
    • Only with const strings
  5. What's wrong with if (x = 5)?

    • It assigns 5 to x instead of comparing, so the condition is always true
    • Nothing
    • It doesn't compile
    • It compares the address of x