Language 1 of 10 · Topic 0.5

Control Flow: Conditionals (if, else-if, switch-case)

1Concept

Conditionals branch program execution based on truthiness (in C, 0 is False, any non-zero value is True). switch statements jump directly to case labels via jump tables. Each case requires an explicit break statement, otherwise execution falls through into subsequent cases.

2Architecture Diagram

[Condition Evaluation]
      |
     / \
    /   \
 [TRUE] [FALSE]
   |       |
   v       v
[Action] [Else]

3Code Example

Stage 0 Language Foundations
#include <stdio.h>

typedef enum {
    LOG_INFO,
    LOG_WARN,
    LOG_ERROR,
    LOG_FATAL
} LogLevel;

void handle_log(LogLevel level, const char *msg) {
    switch (level) {
        case LOG_INFO:
            printf("[INFO] %s\n", msg);
            break;
        case LOG_WARN:
            printf("[WARN] %s\n", msg);
            break;
        case LOG_ERROR:
        case LOG_FATAL: // Intentional fallthrough for high severity
            printf("[CRITICAL] %s (Level code: %d)\n", msg, level);
            break;
        default:
            printf("[UNKNOWN] %s\n", msg);
            break;
    }
}

int main(void) {
    handle_log(LOG_INFO, "Server socket bound successfully.");
    handle_log(LOG_WARN, "Disk capacity at 85%.");
    handle_log(LOG_FATAL, "Database connection terminated.");
    return 0;
}

4Expected Output

[INFO] Server socket bound successfully.
[WARN] Disk capacity at 85%.
[CRITICAL] Database connection terminated. (Level code: 3)

5Key Takeaways

  • C treats any non-zero integer as True and 0 as False.
  • Missing a break in switch-case leads to silent fallthrough bugs.
  • Enums in C are integer constants checked at compile time.