57. State Machine Using Function Pointers

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

void state_init()    { printf("Init"); }
void state_load()    { printf("Load"); }
void state_execute() { printf("Execute"); }
void state_exit()    { printf("Exit"); }

void (*start_arr[4])();

void run_state_sequence(int start) {
    for(int i=0;i<3;i++)
    {
        start_arr[(start+i)%4]();
        if(i!=2) printf("\n");
    }
}

int main() {
    int start;
    start_arr[0] = state_init;
    start_arr[1] = state_load;
    start_arr[2] = state_execute;
    start_arr[3] = state_exit;
    scanf("%d", &start);
    run_state_sequence(start);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote