Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 269
StaticCrazee Avatar asked May 16 '26 18:05

StaticCrazee


1 Answers

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
like image 66
M Oehm Avatar answered May 18 '26 09:05

M Oehm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!