开发者

Question about "goto" in C

I am trying to understand a C code. In 开发者_如何学Pythonsome part there is:

for ...{
    if condition{
       a=1;
       break;
    }
}

which in a later version is changed to:

for ...{
    if condition{
       goto done;
    }
}
done: a=1;

From my point of view, both vesions should give the same result, but it does not happen. Do you know why?

CORRECTION: The fix is:

for ...{
    if condition{
       goto done;
    }
}

            goto notdone;
            done: 
                ok=0;
            notdone:


It depends on whether the for-loop has any other exit conditions.

  • In the first example, a=1 only happens for that specific exit condition in the if-statement.

  • In the second example, a=1 happens in all scenarios that exit the loop. It can only be circumvented using a return statement, or another goto statement.


In the second version, a=1 is eventually executed even though condition was false, simply because the control flow eventually reaches done: after the loop condition is no longer satisfied.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜