Model a traffic light where each state is a function that returns the next state. A function cannot return its own pointer type directly, so wrap it in a struct.
Solution
main.c
#include <stdio.h>
struct state;
typedef struct state (*state_fn)(void);
struct state { state_fn next; const char *name; }; /* wrapper breaks the recursive type */
struct state green(void);
struct state yellow(void);
struct state red(void);
struct state green(void) { return (struct state){yellow, "YELLOW"}; }
struct state yellow(void) { return (struct state){red, "RED"}; }
struct state red(void) { return (struct state){green, "GREEN"}; }
int main(void) {
struct state s = {green, "GREEN"};
for (int tick = 0; tick < 5; tick++) {
printf("%s%s", s.name, tick < 4 ? " -> " : "\n");
s = s.next();
}
return 0;
}
Output Verified by compiling and running
GREEN -> YELLOW -> RED -> GREEN -> YELLOW
"A function returning a pointer to a function like itself" cannot be written in C because the type would be infinite. Returning a struct that contains the pointer solves it.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!