我需要编写一个自动机代码,并且我遇到了计算 goto 的旧需求(ala fortran4 :) )
我需要在可移植 ansi-C 中对此进行编码。
我想远离“不要这样做”,远离 longjmp/setjmp,远离嵌入式 ASM(),远离非 ansi-C 扩展。
有人知道怎么做吗?
最佳答案
就像我在评论中所说的那样,尽管您请求不要使用 goto 之外的任何内容,但标准 C 没有提供任何东西。
适本地设计您的状态,并将指向它的指针传递给处理函数以供它们修改。这样处理程序就可以设置下一个要调用的函数。像这样的事情:
struct state;
typedef void state_func(struct state*);
#define NULL_ACTION_ADDRESS (state_func*)0
struct state {
state_func *action;
int value1;
int value2;
};
#define INIT_STATE { initial_action, -1, -1}
state_func initial_action;
state_func handle_a;
state_func handle_b;
int main(void) {
struct state s = INIT_STATE;
while(s.action != NULL_ACTION_ADDRESS) {
(*s.action)(&s);
}
return 0;
}
void initial_action(struct state* ps) {
ps->action = &handle_a;
}
void handle_a(struct state* ps) {
ps->action = &handle_b;
}
void handle_b(struct state* ps) {
ps->action = NULL_ACTION_ADDRESS;
}
关于C89(再次)计算 goto 如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43832336/