C Programming: Memory, Pointers and the Stack ยท Structs and Types
Name a set of constants with enum, give types short names with typedef, and step a traffic light.
#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;
}switch (l) {.case GREEN: return YELLOW.next_light() has finished, so its variables are gone. The value it returned, {light: YELLOW, seconds: 30}, is stored in s.switch (l) {.case YELLOW: return RED.next_light() has finished, so its variables are gone. The value it returned, {light: RED, seconds: 30}, is stored in s.0 30.0.