要使用goto语句或没有? [英] To use goto or not?

查看:135
本文介绍了要使用goto语句或没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这问题听起来老套,但我在这里的情况。

This question may sound cliched, but I am in a situation here.

我想实现一个有限状态自动解析C中的某个字符串当我开始写code,我实现了code可以更具可读性,如果我使用的标签来标​​记不同的状态并使用goto语句从一个状态跳到另一个视具体情况来了。

I am trying to implement a finite state automaton to parse a certain string in C. As I started writing the code, I realised the code may be more readable if I used labels to mark the different states and use goto to jump from one state to another as the case comes.

使用标准的断裂和标志变量,在这种情况下相当繁琐,难以跟踪的状态。

Using the standard breaks and flag variables is quite cumbersome in this case and hard to keep track of the state.

什么方法比较好?比什么都重要,我担心它可能会留下不好的IM pression我的老板,因为我在实习的机会。

What approach is better? More than anything else I am worried it may leave a bad impression on my boss, as I am on an internship.

推荐答案

使用转到实施状态机往往是有道理的。如果你真的关心使用goto语句,一个合理的选择往往是有一个状态变量,您修改和开关基于语句:

Using a goto for implementing a state machine often makes good sense. If you're really concerned about using a goto, a reasonable alternative is often to have a state variable that you modify, and a switch statement based on that:

typedef enum {s0,s1,s2,s3,s4,...,sn,sexit} state;

state nextstate;
int done = 0;

nextstate = s0;  /* set up to start with the first state */
while(!done)
   switch(nextstate)
      {
         case s0:
            nextstate = do_state_0();
            break;
         case s1:
            nextstate = do_state_1();
            break;
         case s2:
            nextstate = do_state_2();
            break;
         case s3:
             .
             .
             .
             .
         case sn:
            nextstate = do_state_n();
            break;
         case sexit:
            done = TRUE;
            break;
         default:
            /*  some sort of unknown state */
            break;
      }

这篇关于要使用goto语句或没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆