CKTIS / C++
if — conditional statement
The if statement selects a branch using a condition contextually converted to bool. Learn optional else branches, else if chains, initialization before the condition, and the distinction between ordinary if, if constexpr, and if consteval.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
if (condition) { statements; }
if (condition) { statements; } else { statements; }
if (init-statement condition) { statements; } else { statements; }
if constexpr (condition) { statements; } else { statements; }
if consteval { statements; } else { statements; }
if !consteval { statements; } else { statements; }if executes its first branch when the condition, contextually converted to bool, is true. For false, it executes the optional else; without one, it skips the branch. For integers, zero means false and a nonzero value means true.
else if is a nested if, not a separate keyword. An else binds to the nearest if without an else. Use {} for unambiguous grouping. An accidental semicolon in if (condition); creates an empty branch.
The form if (init-statement condition) performs initialization before testing the condition. The terminating semicolon is part of init-statement, so no extra semicolon goes before condition. A variable declared in the init-statement is available in the condition and both branches, but not after the entire if. The condition can also declare a variable, such as if (int n = 3).
if constexpr requires a condition that is a constant expression after conversion to bool. Its discarded branch is not instantiated in a template once the substituted condition is no longer dependent. This does not permit arbitrary invalid code outside templates. if consteval selects its first branch in a manifestly constant-evaluated context. This includes trial constant evaluation of an initializer, even when constant evaluation is not required. if !consteval reverses the selection. These forms require {} blocks and have no parenthesized condition.
This entry targets C++23. The linked document is an evolving working draft, not a frozen C++23 text. In the example, score is visible throughout the chain, and the result is pass.
Examples
#include <iostream>
int main() {
if (int score = 72; score >= 90) {
std::cout << "excellent\n";
} else if (score >= 60) {
std::cout << "pass\n";
} else {
std::cout << "retry\n";
}
}
Result
pass
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.