C++ Cheat Sheet: Control Structures

1. Conditional Statements

if Statement
if (condition) {
    // Code executes if condition is true
}
if-else Statement
if (condition) {
    // Executes if true
} else {
    // Executes if false
}
if-else if-else Ladder
if (condition1) {
    // Executes if condition1 is true
} else if (condition2) {
    // Executes if condition2 is true
} else {
    // Executes if none are true
}
Ternary Operator
result = (condition) ? valueIfTrue : valueIfFalse;

2. Switch Statement

switch-case Syntax
switch (expression) {
    case value1:
        // Code block
        break;
    case value2:
        // Code block
        break;
    default:
        // Default code block
}

🔹 Notes:

  • expression must be of integral or enum type.
  • Use break to avoid fall-through.
  • default is optional.

3. Loops

while Loop
while (condition) {
    // Executes while condition is true
}
do-while Loop
do {
    // Executes at least once
} while (condition);
for Loop
for (initialization; condition; update) {
    // Executes until condition is false
}
Range-based for Loop (C++11+)
for (auto var : container) {
    // Iterates through elements
}

4. Branching Statements

break Statement
for (int i = 0; i < 10; i++) {
    if (i == 5) break;
}
continue Statement
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) continue;
    // Skips even numbers
}
return Statement
return;         // For void functions
return value;   // For functions with return types