0

I am trying to understand a C code. In some 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:
Open the way
  • 26,225
  • 51
  • 142
  • 196

2 Answers2

6

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.

Stéphan Kochen
  • 19,513
  • 9
  • 61
  • 50
3

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.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • @Werner: By using version 1? No, seriously, it depends on what behaviour you want. If you want the behaviour of version 1, use version 1. If you want the behaviour of version 1, but you cannot use version 1 for some reason, tell us the reason so that we can suggest an alternative. The easiest solution would be to move `a=1` back inside the condition. – Heinzi Nov 28 '10 at 17:49