C Programming: Memory, Pointers and the Stack ยท Control Flow

if, else if and switch

Choose a branch with if / else if / else, and match exact values with switch, where break matters.

if_switch.c

#include <stdio.h>

int main(void) {
    int temp = 31;
    const char *feel;
    if (temp > 30) {
        feel = "hot";
    } else if (temp > 15) {
        feel = "mild";
    } else {
        feel = "cold";
    }
    int day = 2;
    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        default:
            printf("Another day\n");
    }
    printf("%s\n", feel);
    return 0;
}

Step by step

  1. temp is created on the stack with the value 31. feel is created on the stack with the value ?.
  2. 31 > 30 is true, so this branch runs and the others are skipped.
  3. feel changes from ? to "hot".
  4. day is created on the stack with the value 2.
  5. switch jumps straight to the case matching day: case 2.
  6. It prints Tuesday.
  7. break leaves the switch.
  8. It prints hot.
  9. The method returns 0.
  10. Tuesday and hot. if tests conditions in order; switch jumps to a matching value.