StaticCrazee
StaticCrazee

Reputation: 297

Incrementing in for loop condition

While browsing the Linux source code, I came across the following line:

int tmp;    
for (tmp = PIDTYPE_MAX; --tmp >= 0; )

Why not do:

for (tmp = PIDTYPE_MAX; tmp >= 0; tmp--)

Is this another sort of for loop optimization?

Upvotes: 3

Views: 145

Answers (2)

Maaz
Maaz

Reputation: 21

In first case the value of temp will be decremented before entering into the loop. While in second case the value of temp will be decremented after execution of loop body.

Upvotes: 0

M Oehm
M Oehm

Reputation: 29126

Your loops are not equivalent: The second loop includes the upper bound PIDTYPE_MAX, the first one doesn't.

Decrementing the iterator variable before the loop body ensures that the condition 0 <= tmp < PIDTYPE_MAX is always true in the loop. This is in fact the canonical backwards loop in C, where lower bounds are inclusive and upper bound are exclusive.

Note that the first loop requires a signed integer to work, so that the test for tmp >= 0 makes sense. (It would always be true for unsigned integers.)

Unsigned types like size_t are often used for array indices and counts, which cannot be negative. The respective loops are:

for (size_t i = 0; i < N; i++) ...     // iterate over [0, N) forwards
for (size_t i = N; i-- > 0; ) ...      // iterate over [0, N) backwards

Upvotes: 5

Related Questions