LearnFrenzy
Sign in Take a free test

Complicated Declarations · Complicated Declaration Programs · Question 3

Traffic-light state machine with function pointers in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links