3

Possible Duplicate:
C/C++: is GOTO faster than WHILE and FOR?

I know this has been asked for many times, but I never got an answer which satisfies me by googling.

I read somewhere that every loop(for/while/do-while/untill) will be eventually be converted to goto statements internally, Is that True?

If not, Which is the best loop to use as per the performance wise? Let me know if anybody knows?

1
  • 2
    The real answer is, of course: It doesn't matter and even if it did, every speed difference would be made moot by the readability and maintainability differences.
    – user395760
    Apr 1, 2011 at 19:53

4 Answers 4

7

The correct answer is to learn enough assembly in order to read through your compiler's generated code.

However, these micro-optimizations usually don't matter (except for very specific areas).

1
  • 2
    Learning how C programs get compiled into assembly is a great thing to do. It will greatly increase your understanding of C programs in general. Apr 1, 2011 at 19:46
4

They say "converted to goto statements internally" as meaning machine/assembly does not have a notion of loops, just compare/jump to label instructions which would equate to if/goto.

Any loop construct you write will be reduced to this.

1

With any decent compiler, this won't make any difference at all. Each type of loop is likely to result in comparable assembly code.

It's best to use a type of loop that most naturally expresses what you want to achieve; this also makes it likely that the compiler can optimize it well.

1

The compiler translates all your source code into the assembler language for the target processor. The assembler language is very low level and does not have constructs like for and while. The assembler language has uses jump statements which are equivalent to goto in your high level language program.

Performance wise it should not really matter which loop construct you use.

If you want to see and compare the generated assembler code you can invoke gcc like so: gcc main.c -S -O2 and take a look at the generated main.S file which now contains the assembler code for your program.

Make sure to include the -O2 or -O3 optimization flags because comparing code which has been build without optimizations turned on does not make much sense.

Not the answer you're looking for? Browse other questions tagged or ask your own question.