c++cperformancefor-loopwhile-loop

Is there any performance difference between for() and while()?


Or is it all about semantics?


Solution

  • Short answer: no, they are exactly the same.

    Guess it could in theory depend on the compiler; a really broken one might do something slightly different but I'd be surprised.

    Just for fun here are two variants that compile down to exactly the same assembly code for me using x86 gcc version 4.3.3 as shipped with Ubuntu. You can check the assembly produced on the final binary with objdump on linux.

    int main()
    {
    #if 1
        int i = 10;
        do { printf("%d\n", i); } while(--i);
    #else
        int i = 10;
        for (; i; --i) printf("%d\n", i);
    #endif
    }
    

    EDIT: Here is an "oranges with oranges" while loop example that also compiles down to the same thing:

        while(i) { printf("%d\n", i); --i; }