I strongly disagree with the accepted answer, which says
The biggest problem with using a for-loop to do this is that you are wasting CPU power.
That is a problem, but it isn't the biggest problem by far. The biggest problem is that int
is 32 bits on many platforms, including 64-bit Windows, and 100000000000
is out of the range of a 32-bit int
. Depending on how such constants are handled, i
may be incremented until it overflows. The behavior of int
on overflow is undefined.
Modern optimizing compilers are smart enough to recognize that this code has undefined behavior, but many are not smart enough to do anything sane with that information. Clang, particularly, is notorious for doing crazy things with undefined code, such as emitting no machine language instructions at all for the entire function, not even a ret
instruction, leaving the instruction pointer to wander off into no man's land and perhaps execute code from some unrelated function that happens to be nearby in memory.
The answers that imply that the worst thing the compiler could do is delete the loop are wrong. Much worse things can happen.
On platforms where 100000000000
is a valid int
, the compiler will probably just delete the loop, so wasting CPU power still isn't the biggest problem on those platforms; the biggest problem is that it just won't work. If you disable optimizations, it will probably work as intended, but writing code that only works when optimizations are disabled is not considered good programming practice, unless the reason is that the optimizer is buggy, which is not the case here.