Chapter 8: Control Flow

Control flow statements allow your program to make decisions and repeat actions. They are the building blocks of logic in any procedural language.

I. Selection Statements

Selection statements allow your code to branch based on conditions.

1. if, else if, and else

The most common decision-making structure.

if (score >= 90) {
    printf("Grade A\n");
} else if (score >= 80) {
    printf("Grade B\n");
} else {
    printf("Grade F\n");
}

2. switch Statement

A more efficient way to branch when testing a single variable against multiple constant values. It uses a jump table internally, making it faster than a long chain of if-else.

switch (command) {
    case 'q':
        exit(0);
        break; // Crucial to prevent 'fall-through'
    case 'r':
        printf("Restarting...\n");
        break;
    default:
        printf("Unknown command.\n");
}

II. Iteration Statements (Loops)

Loops repeat a block of code multiple times.

  1. for Loop: Best when you know the number of iterations in advance.
    for (int i = 0; i < 10; i++) {
        printf("%d ", i);
    }
    
  2. while Loop: Best when the number of iterations is unknown and depends on a condition.
    while (x > 0) {
        x /= 2;
    }
    
  3. do-while Loop: Guaranteed to run at least once before checking the condition.
    do {
        printf("Menu: 1. Start 2. Exit\n");
    } while (choice != 2);
    

III. Jump Statements

Jump statements alter the normal linear flow of execution.

  • break: Immediately exits the innermost loop or switch.
  • continue: Skips the rest of the current iteration and jumps to the next one.
  • return: Exits the function and optionally returns a value.
  • goto: Jumps to a labeled statement. Avoid using this in modern code as it creates "spaghetti logic."

IF ConditionOne BranchFOR LoopRepeated CodeSWITCHMulti-Branch

IV. Infinite Loops

In systems programming (like operating system kernels or microcontrollers), we often need a program that never stops.

// Method 1: while
while (1) {
    /* Keep running */
}

// Method 2: for (preferred by some)
for (;;) {
    /* Keep running */
}

V. Boolean Logic in Conditions

In C, any non-zero value is true, and zero is false. This is a powerful but dangerous feature.

if (5) { /* This will always run */ }
if (0) { /* This will never run */ }

Always use explicit comparisons (e.g., if (x != 0)) if you want your intent to be clear to others.