Understanding the if Statement in C++

The if statement allows you to execute a block of code only if a specified condition is true. It is fundamental for decision-making in programming.

Syntax of the if Statement

if (condition) {
    // Code to execute if condition is true
}

Example: Using the if Statement

#include <iostream>

int main() {
    int age = 20;
    if (age >= 18) {
        std::cout << "You are eligible to vote." << std::endl;
    }
    return 0;
}

Explanation: The program checks if age is greater than or equal to 18. Since it is, the message is printed to the console.

Key Takeaways

  • The if statement executes code only when the condition is true.
  • Conditions are Boolean expressions that evaluate to true or false.
  • Curly braces {} enclose the code block associated with the if statement.