100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

if Statement in C++

Learn how the C++ `if` statement evaluates a boolean condition and conditionally executes a block of code, with syntax, flow, and examples.

Decision MakingBeginner6 min readJul 7, 2026
Analogies

1. Intro

The if statement is the most basic decision-making construct in C++. It lets a program test a condition and run a block of code only when that condition is true. Decision-making statements let a program choose between different paths of execution based on data available at runtime, and if is the building block every other conditional construct (if-else, else if ladder, switch) is built on top of.

🏏

Cricket analogy: A fielding captain testing 'is the batsman out of his crease?' before calling for a run-out appeal is a basic decision, just as if is the foundational construct every more complex decision in C++ builds on.

2. Syntax

cpp
if (condition) {
    // statement(s) executed only if condition is true
}

3. Explanation

The condition inside the parentheses must evaluate to a boolean value (true/false), or to an expression that is implicitly convertible to bool — any nonzero value is treated as true, and 0 is treated as false. If the condition evaluates to true, the statement block runs; otherwise, it is skipped entirely and control moves to the next statement after the if block. If the body contains only a single statement, the curly braces {} are technically optional, but omitting them is considered bad practice because it makes code error-prone when new lines are added later.

🏏

Cricket analogy: Any nonzero run total from a ball being treated as 'runs scored' (true) while exactly zero runs is a dot ball (false) mirrors how C++ treats any nonzero value as true and 0 as false in an if condition.

4. Example

cpp
#include <iostream>
using namespace std;

int main() {
    int age = 20;

    if (age >= 18) {
        cout << "You are eligible to vote." << endl;
    }

    cout << "Program finished." << endl;
    return 0;
}

5. Output

text
You are eligible to vote.
Program finished.

6. Key Takeaways

  • The if statement executes a block only when its condition evaluates to true.
  • Any nonzero numeric value is treated as true; 0 is treated as false.
  • If there is no matching else, a false condition simply skips the block and execution continues after it.
  • Always use {} around the body, even for a single statement, to avoid bugs when the code is edited later.

Practice what you learned

Was this page helpful?

Topics covered

#CStudyNotes#Programming#IfStatementInC#Statement#Syntax#Explanation#Example#StudyNotes#SkillVeris#ExamPrep