Control Flow
If-Else Statements
Conditional branching in C++
Interview: Basic control flow
If-Else Statements
Conditional branching is how programs make decisions. The if-else construct evaluates a boolean expression and routes execution along different paths. Under the hood, the compiler translates these to conditional jump (branch) instructions in native machine code.
C++17: If with Initializer
C++17 introduced the ability to initialize a variable directly inside the if condition. This scopes the variable to only exist within the if-else block, preventing polluting the enclosing scope.
Ternary (Conditional) Operator
The ternary operator condition ? expr_true : expr_false is a compact single-line conditional. It is an expression (returns a value), unlike if-else which is a statement. Both branches must produce values of the same or compatible type.
Constexpr If (C++17)
if constexpr evaluates the condition at compile time. The discarded branch is not instantiated, enabling template metaprogramming patterns that previously required template specialization.
Interview Corner
Q: What is the difference between if constexpr and a regular if statement in templates?
A: With a regular if, both branches must be valid code even if never executed — leading to compile errors in templates. With if constexpr, only the selected branch is instantiated, so the other branch can contain type-specific code that would be invalid for other template instantiations.
Q: Why should you avoid side effects inside if conditions?
A: Side effects (like assignment or function calls with state changes) in conditions make code hard to reason about. If the condition short-circuits (via && or ||), the side effect may not execute at all, leading to subtle bugs.
Common Pitfalls
- Assignment in condition: Writing
if (x = 5)instead ofif (x == 5). The compiler may warn, but it compiles. Useif ((x = 5))intentionally to suppress warnings when assignment is deliberate. - Dangling else: Without braces, an else binds to the nearest if, which may not be the intended if. Always use braces
{}even for single-line bodies.
Best Practices
- Always use braces
{}for if-else bodies, even for single statements, to prevent accidental dangling-else bugs. - Prefer the C++17 if-initializer to scope loop variables tightly and reduce namespace pollution.
- Use
if constexprin templates to eliminate dead code branches and achieve clean compile-time branching.