For (;;) … While (condition…) …
Why not use while in both situations, so while(1)… instead of for(;;) ?
For (;;) … While (condition…) …
Why not use while in both situations, so while(1)… instead of for(;;) ?
There’s no other occasion I can think of where an expression becomes vacuously true by being omitted. If it were conceptually coherent you’d write for(;true;). I guess maybe the reason they made C accept for(;;) but not while() is because while() might confuse a compiler by looking like a function call.
Syntax wise, it doesn't really matter. "for" just happens to be the keyword that allows omitting the condition. "While" effectively means "during which". "For" on the other hand has a significantly more flexible meaning; it seems reasonable to me that the for keyword would be more flexible. Syntax wise, the most explicit thing to have in a language would be a "forever" keyword of some sort.
Because some compilers warn that the condition is constant and suggest you rewrite it as for (;;)
for (;;) is less typing.
for (;;) has always been the idiomatic way to do an infinite loop.
FWIW https://github.com/robohack/ucb-csrg-bsd contains both variants.
Not a problem now.
They lack the code to remove a tautological test.
But approximately all compilers these days are optimising compilers, so don’t worry about it.
Because normalising is an optimization, and these compilers didn't have any optimisations. That was normal back then. You had a whole separate product that was specifically an 'optimising compiler'. These days that's implicit and we just say 'compiler'.
These days, even -O0 will canonicalise the condition! That's how normalised it is! But I guess this is done during translation to IR, rather than as an 'optimisation'.
We’re talking compiler implementation and optimisation - not coding aesthetics.
> Your link even shows this.
Yes the link shows how it doesn't matter today! Because almost all compilers are now 'optimising compilers'!
> There is no `cmp` opcode used. A simple unconditional `jmp` is used.
Oh my god that's the entire point! That's how compilers work now. They always optimise. They didn't used to do that.
The compiler checks the truthiness of the value in the while condition. Modern compilers remove it with either a tautology check, or a shortcut during IR building. They didn't used to do that, so there used to be a cost, which is why people started cargo-culting the for equivalent.
Here's a worked example using a niche compiler with a very different architecture that unusually still doesn't canonicalise during building.
Compare
https://godbolt.org/z/3v3anacM8
and
https://godbolt.org/z/chWjsen4s
See the difference? See the 'cmp eax, 1' and then how it goes away under optimisation?