Curious about difference between 'for' and 'while', CPU wise

Hi everyone.

I have a very small question out of curiosity. I learned by myself and testing that you can add more expressions inside the for loop structure, which can lead to interesting (even if obfuscated) code. This made me realize something. Consider this:

1
2
3
while (node->next != 0) {
    node = node->next;
}

equals this:

1
2
3
for (;node->next != 0;) {
    node = node->next;
}

And consider this:

Wikipedia article For loop wrote:
the initializer and counting expressions are treated as no-ops when omitted

My question is: will the omitted expressions in the for structure execute a NOP on the processor? If it does and in the case of the last one, will it execute it after every loop?
No, the compiler is smart enough to optimise NOPs away.
My question is: will the omitted expressions in the for structure execute a NOP on the processor?

No, of course not. no-op is to be taken literally (i.e. no operation), it doesn't have anything to do with the corresponding x86 instruction.
However, you really need to read this and the articles linked on that page:
http://en.wikipedia.org/wiki/Compiler_optimization
...as most of your concerns about performance will turn out to be unnecessary.
Athar wrote:
However, you really need to read this and the articles linked on that page:

Not really, right now I'm not THAT concerned on performance. I just wanted to know if I'd be losing something by using for instead of while.

But thanks for the answers!
Well, the point the articles were supposed to bring across is that modern compilers are able to perform rather complex optimizations, so something as trivial as making sure that these two loop variants run equally fast is definitely not a problem.
It's not even necessary to perform optimizations. A for can be treated by the compiler as pure syntactic sugar and transformed into a while:
1
2
3
4
5
6
7
8
9
10
11
//Note: if B must be non-empty
for (A;B;C) D
//becomes
{
    //Empty statements, as in ";;" generate no code.
    A;
    while (B){
        D
        C;
    }
}
The case where D is empty doesn't have an equivalent while translation. Without any optimizations, many compilers stupidly generate for while (1) a check for the truthness of 1. for (A;;C), on the other hand, generates a loop with unconditional jumps.

All of this said, these points are so minor that they're hardly ever worth considering.
Topic archived. No new replies allowed.