我正在尝试编写一个循环结构并返回枚举变量的方法。所述方法是lookup_transitions()
,这是我的代码:(我使用enum作为指向我的函数的指针,因为在这种情况下我不确定如何有效地使用int指针)。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
enum ret_codes { ok, fail};
//forward declaration of functions
enum ret_codes s0_state(int);
enum ret_codes s1_state(int);
enum ret_codes s2_state(int);
/* pointer to the functions*/
enum ret_codes (* state[])(int) =
{
s0_state,
s1_state,
s2_state
};
enum state_codes { s0, s1, s2 };
struct transition {
enum state_codes src_state;
enum ret_codes ret_code;
enum state_codes dst_state;
};
struct transition state_transitions[] = {
{s0, ok, s1},
{s0, fail, s0},
{s1, ok, s2},
{s1, fail, s0}};
//function definitions
//these were previously returning int, changed to enum ret_codes
enum ret_codes s0_state(int digit){
puts ("\nState s0 (RESET):");
puts ("(alarm inactive)");
puts ("Enter password to arm alarm, or 'e' to cancel: ");
if (digit != 5){
return fail;
}
return ok;
}
enum ret_codes s1_state(int digit){
puts ("\nState s1:\n");
if (digit != 6)
return fail;
return ok;
}
enum ret_codes s2_state(int digit){
puts ("\nState s2, (alarm inactive): \n");
if (digit != 3)
return fail;
return ok;
}
enum state_codes lookup_transitions(enum state_codes sc, enum ret_codes myRC){
//should return s0,s1 or s2
enum state_codes result = sc;
for (int i = 0; i < sizeof(state_transitions)/sizeof(state_transitions[0]); ++i)
{
if (state_transitions[i].src_state == sc && state_transitions[i].ret_code == myRC)
{
result = state_transitions[i].dst_state;
}
}
return result;
}
#define S0_STATE s0
int main(int argc, char *argv[] ){
int input;
enum state_codes curr_state = S0_STATE;
enum ret_codes (* state_fun)(int);
state_fun = state[curr_state]; //start at s0
enum ret_codes rc;
while (true){
input = getchar();
if( input != 'e') {
rc = state_fun(input);
curr_state = lookup_transitions(curr_state, rc);//should return s0,s1 or s2
}
input = getchar();
}
puts ("\nProgram completed successfully");
return 0;
}
我的lookup_transitions()方法似乎没有正确迭代数组。你能帮我搞清楚吗?