C Programming: Memory, Pointers and the Stack ยท Structs and Types

typedef and enum

Name a set of constants with enum, give types short names with typedef, and step a traffic light.

typedef_enum.c

#include <stdio.h>

typedef enum { RED, YELLOW, GREEN } Light;

typedef struct {
    Light light;
    int seconds;
} Signal;

Light next_light(Light l) {
    switch (l) {
        case GREEN: return YELLOW;
        case YELLOW: return RED;
        default: return GREEN;
    }
}

int main(void) {
    Signal s = {GREEN, 30};
    s.light = next_light(s.light);
    s.light = next_light(s.light);
    printf("%d %d\n", s.light, s.seconds);
    return 0;
}

Step by step

  1. An enum value is a named int: GREEN is 2.
  2. next_light(GREEN) returns YELLOW.
  3. Line runs: switch (l) {.
  4. Line runs: case GREEN: return YELLOW.
  5. next_light() has finished, so its variables are gone. The value it returned, {light: YELLOW, seconds: 30}, is stored in s.
  6. Again.
  7. Line runs: switch (l) {.
  8. Line runs: case YELLOW: return RED.
  9. next_light() has finished, so its variables are gone. The value it returned, {light: RED, seconds: 30}, is stored in s.
  10. It prints 0 30.
  11. The method returns 0.
  12. light 0 (RED), 30 seconds.