`if` — C++ Keyword

`if` — C++ Keyword

The if keyword in C++: conditionally executes a statement when a condition is true.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

if

Conditionally executes a statement or block when the given condition evaluates to true. Since C++17, an optional init-statement may appear before the condition.

Syntax

if (condition) statement
if (condition) statement else statement
if constexpr (condition) statement           // C++17 – compile-time branch
if (init-statement; condition) statement     // C++17 – init-statement form

Example

#include <print>

int compute() { return 42; }

int main() {
    int x = 10;

    if (x > 5) {
        std::println("x is greater than 5");
    } else {
        std::println("x is 5 or less");
    }

    // C++17 init-statement: val is scoped to the if/else block
    if (int val = compute(); val > 0) {
        std::println("positive: {}", val);
    }
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}