DevAcademia lesson/C++ Basics
if Statement
Topic progressTopic 38 of 109 - 35% complete
~7 min lesson20 learning blocks5 code examples1 checks/interactions
Lesson outline
Introduction to if Statements
The if statement is the simplest conditional control structure in C++. It lets you run specific code only when a given condition evaluates to true.
This is essential for implementing decision-making logic in your programs.
Basic Syntax
Practical Example
Single Statement if
If the body of the if contains only one statement, the braces can be omitted:
If with Initializer (C++17)
Since C++17, you can initialize a variable as part of the if. The variable's scope is limited to the if/else statement.
Common Pitfalls
- Assignment vs comparison:
if (x = 0)assigns 0 and tests false; use==for comparison. Many teams preferif (0 == x)to catch accidental assignment. - Stray semicolon:
if (cond); { ... }ends theifprematurely and the block always executes. - Side effects in conditions: Avoid complex function calls with side effects inside the condition.
- Dangling else:
elsebinds to the nearest unmatchedif; use braces to make intent explicit.
Was this topic clear?