In many programming competitions I have seen people write this type of for
-loop
for(i = 0; i < (1 << 7); i++)
Unless I am missing something, that's the same as
for(i = 0; i < 128; i++)
Why use the (1 << 7)
version?
Isn't calculating the condition every time an unnecessary overhead?
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."