Technical reasons behind formatting when incrementing by 1 in a 'for' loop? Technical reasons behind formatting when incrementing by 1 in a 'for' loop? c c

Technical reasons behind formatting when incrementing by 1 in a 'for' loop?


Everybody loves their micro-optimizations, but this would not make a difference as far as I can see. I compiled the two variations with g++ on for Intel processors without any fancy optimizations and the results are for

for(int i = 0; i < 5; i++)
    movl $0, -12(%ebp)    jmp L2L3:    leal    -12(%ebp), %eax    incl    (%eax)L2:    cmpl    $4, -12(%ebp)    jle L3

for(int i = 0; i != 5; ++i)
    movl    $0, -12(%ebp)    jmp L7L8:    leal    -12(%ebp), %eax    incl    (%eax)L7:    cmpl    $5, -12(%ebp)    jne L8

I think jle and jne should translate to equally fast instructions on most architectures. So for performance, you should not distinguish between the two. In general, I would agree that the first one is a little safer and I also think more common.


EDIT (2 years later): Since this thread recently got again a lot of attention, I would like to add that it will be difficult to answer this question generally. Which versions of code are more efficient is specifically not defined by the C-Standard [PDF] (and the same applies to C++ and probably also for C# ).

Section 5.1.2.3 Program execution

ยง1 The semantic descriptions in this International Standard describe the behavior of an abstract machine in which issues of optimization are irrelevant.

But it is reasonable to assume that a modern compiler will produce equally efficient code and I think that in only very rare cases will the loop-test and the counting expression be the bottleneck of a for-loop.

As for taste, I write

for(int i = 0; i < 5; ++i)


If for some reason i jumps to 50 in the loop, your version would loop forever. The i < 5 is a sanity check.


The form

for (int i = 0; i < 5; i++)

is idiomatic, so it's easier to read for experienced C programmers.Especially when used to iterate over an array.You should write idiomatic code whenever possible as it reads faster.

It is also a little safer in situations when you modify i inside the loop or use an increment different then 1.But it's a minor thing.It's best to carefully design your loop and add some asserts to catch broken assumptions early.