HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to C++VariablesData TypesOperatorsStringsVectors (vector)Conditions (if / switch)Loops (for / while)FunctionsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & Vector
🔁 Condition & Loop
🧩 Function & Class
C++›Conditions (if / switch)

Conditions (if / switch)

Making decisions with if-else, else if, and switch.

Simple enough for a 5-year-old to understand

if / else

Example code
1
#include <iostream>
2
using namespace std;
3
int main() {
4
int score = 75;
5
if (score >= 50) {
6
cout << "Passed" << endl;
7
} else {
8
cout << "Failed" << endl;
9
}
10
return 0;
11
}

About this topic

In C++, a condition produces a boolean value, but it also accepts an integer: zero is false, and any other value is true. This is a flexibility inherited from C, which also brings along C's pitfalls.

The most common pitfall is confusing a single equals sign with a double equals sign. Because assignment produces a value, writing it inside a condition does not cause a compilation error; the compiler issues a warning, but the code runs and silently produces incorrect results.

C++17 made a useful addition to the condition structure: you can define a variable inside an if statement. Thus, a variable needed only for that condition does not leak outward and its scope is narrowed. This is a simple arrangement that reduces the probability of errors.

What you will learn

  • the if, else if, and else structure
  • why you should always write curly braces
  • the necessity of break inside a switch
  • defining a variable inside an if statement

When to use?

If a single variable is compared against numerous constants, switch is more readable and the compiler can generate a jump table.

If range checking or text comparison is required, an if chain is used; switch only works with integer and character constants.

Common mistakes

Wrong

#include <iostream>
using namespace std;

int main() {
    int score = 40;
    if (score > 60)
        cout << "Passed" << endl;
        cout << "Congratulations" << endl;
    return 0;
}

Because there are no curly braces, only the first line is bound to the condition; the second line always runs even though it is indented. This bug does not cause a compilation error, it only produces wrong output, and since the indentation looks correct, it is not visually noticeable.

Correct

#include <iostream>
using namespace std;

int main() {
    int score = 40;
    if (score > 60) {
        cout << "Passed" << endl;
        cout << "Congratulations" << endl;
    }
    return 0;
}

Wrong

#include <iostream>
using namespace std;

int main() {
    int level = 2;
    switch (level) {
        case 1:
            cout << "Beginner" << endl;
        case 2:
            cout << "Intermediate" << endl;
        case 3:
            cout << "Advanced" << endl;
    }
    return 0;
}

Because break is not written, execution flows downwards from the matching case: both Medium and Advanced are printed to the screen. C++ inherited this behavior from C and kept it for intentional use, but it usually means a forgotten break.

Correct

#include <iostream>
using namespace std;

int main() {
    int level = 2;
    switch (level) {
        case 1:
            cout << "Beginner" << endl;
            break;
        case 2:
            cout << "Intermediate" << endl;
            break;
        case 3:
            cout << "Advanced" << endl;
            break;
    }
    return 0;
}

Wrong

#include <iostream>
#include <string>
using namespace std;

int main() {
    string role = "admin";
    switch (role) {
        case "admin":
            cout << "Administrator" << endl;
            break;
    }
    return 0;
}

switch only works with integer and character types; it cannot be used with string and the compiler gives a "switch quantity not an integer" error. For text comparison, an if chain or a map mapping text to value is used.

Correct

#include <iostream>
#include <string>
using namespace std;

int main() {
    string role = "admin";
    if (role == "admin") {
        cout << "Administrator" << endl;
    } else {
        cout << "User" << endl;
    }
    return 0;
}

Frequently asked questions

Why is defining a variable inside an if statement good?

The scope of the variable remains limited only to that condition, it does not leak outside. In cases where a function returns both its result and whether it was successful, this pattern produces very clean code and prevents the variable from being used in the wrong place.

How do I notice if I wrote a single equals sign in a condition?

Turn on compiler warnings; GCC gives a "suggest parentheses around assignment used as truth value" warning. The option that turns warnings into errors completely prevents this mistake. In modern compilers, this warning is not on by default, you have to turn it on manually.

Can I always use if instead of switch?

Yes. The reverse is not true: switch cannot compare text, cannot do range checking, and only works with compile-time constants. If there are many constant comparisons, switch is both readable and fast.

Summary

Zero is false, every value other than zero is true.

Always write curly braces even for single-line blocks.

If break is not written inside a switch, the execution flow continues downwards.

switch does not work with string; for text, an if chain is used.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code