Why an expression instead of a constant, in a C for-loop's conditional? Why an expression instead of a constant, in a C for-loop's conditional? c c

Why an expression instead of a constant, in a C for-loop's conditional?


Yes, they are equivalent in behavior.

Then why do people use the (1 << 7) version?

I guess, they use it to document it is a power of 2.

Calculating the condition every time must be an overhead! I am unable to find the reason behind this!

Not really, any normal compiler will replace 1 << 7 by 128 and so both loops will have the same performances.

(C11, 6.6p2) "A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be."


Let's translate each one of these options into plain English:

for(i = 0; i < (1 << 7); i++) // For every possible combination of 7 bitsfor(i = 0; i < 128; i++)      // For every number between 0 and 127

Runtime behavior should be identical in both cases.

In fact, assuming a decent compiler, even the assembly code should be identical.

So the first option is essentially used just in order to "make a statement".

You could just as well use the second option and add a comment above.


1 << 7 is a constant expression, the compiler treats it like 128, there's no overhead in run time.

Without the loop body, it's hard to say why the author uses it. Possibly it's a loop that iterates something associated with 7 bits, but that's just my guess.