Created
October 5, 2019 21:24
-
-
Save MatthaeusHarris/34aeb15f45b1eb2306b8409d295a9aed to your computer and use it in GitHub Desktop.
Quick and dirty state machine with function pointers in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
// Declare three functions that return nothing and accept a single pointer to an int as an argument | |
void state1(int *); | |
void state2(int *); | |
void state3(int *); | |
// Set up our state definitions. Using bare numbers in code itself is an anti-pattern. | |
const int STATE_1 = 0; | |
const int STATE_2 = 1; | |
const int STATE_3 = 2; | |
const int STATE_4 = 3; | |
// Define the state transition functions. These are just toys right now. | |
void state1(int *nextState) { | |
printf("Just entered state %d.\n", STATE_1); | |
printf("Hardcoded to enter state %d.\n", STATE_2); | |
*nextState = STATE_2; | |
} | |
void state2(int *nextState) { | |
printf("Just entered state %d.\n", STATE_2); | |
printf("Hardcoded to enter state %d.\n", STATE_3); | |
*nextState = STATE_3; | |
} | |
void state3(int *nextState) { | |
printf("Just entered state %d.\n", STATE_3); | |
printf("Hardcoded to enter state %d.\n", STATE_4); | |
*nextState = STATE_4; | |
} | |
// Set up our table of function pointers | |
void (*stateFunctions[3])(int *) = {state1, state2, state3}; | |
int main(int argc, char **argv) { | |
// Define an intial state | |
int state = 1; | |
// While we haven't reached the terminal state, continue to call the state transition function as defined by the current state | |
while (state != STATE_4) { | |
(stateFunctions[state])(&state); | |
} | |
printf("Done!\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment