The next traffic light colour
Step through the states of an enum. An easy embedded C problem (Structs, enums and typedef), run and graded in the browser.
easy · Structs, enums and typedef · enums · switch
A traffic light goes red, then green, then yellow, then back to red.
Return the state that follows now.
Starter code
typedef enum {
LIGHT_RED,
LIGHT_GREEN,
LIGHT_YELLOW,
} light_t;
light_t next_light(light_t now) {
return now;
}Example tests
Red turns green
printf("%d\n", next_light(LIGHT_RED) == LIGHT_GREEN);Expected output:
1Green turns yellow
printf("%d\n", next_light(LIGHT_GREEN) == LIGHT_YELLOW);Expected output:
1Learn it first
- Structs, enums and typedef · Grouping values into structs, the dot and the arrow, naming choices with enum, and shorter names with typedef.
More Structs, enums and typedef problems
- Build a struct · Fill in a struct's members and return it.
- Distance between two points · Read the members of two structs passed by value.
- Move a point · Change the caller's struct through a pointer.
- Average the valid readings · Loop over an array of structs and use only some of them.
- Count the LEDs that are on · Combine a struct, an enum member and a loop.