2

what is the between in writing a loop by branching jump statement and a normal loop i.e for example

        main()
        {
        int i=0;
        while(i<9)
        {
          //do something
           i++;
        }

and

        main()
        {
            int i=0;
            label:
             //do something
              i++;
             if(i<9)
              goto label;
         }

is the performance of both of them are equal?

user2416871
  • 543
  • 1
  • 4
  • 13

3 Answers3

10

These two loops are not equivalent: the second one is similar to a do/while loop, not a while loop:

main() {
    int i=0;
    do {
      //do something
       i++;
    } while(i<9);
}

The two should be the same as far as the performance goes; however, the readability of the solution with the goto suffers considerably, so I would refrain from using it in any of your projects.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

The difference is that the first one is a lot easier to read, which is why goto is generally avoided. Also as pointed out in dasblinkenlight's answer the semantics are not the same.

The performance should be about the same, since the CPU has to do jumps in order to implement both. Of course, with a higher-level description of intent (as in the first case) the chance of the compiler being able to optimize something increases.

Perhaps not in this particular case, but in general a more high-level description of what you want to do is to be preferred, and then the looping constructs are better than goto.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
2

In this case, compiler should produce an equivalent output. But I don't think these two examples are equivalent - a while first checks the condition and then decides wheter to execute the body. Your example with the goto first executes the body and then checks the conditions - it behaves more like a do while statement.

You shouldn't use goto in this case, as it reduces readability. gotos are valid in only a limited number of scenarios.

Andrej Palicka
  • 971
  • 1
  • 11
  • 26