5 ms·
The semantics of the for loop with an omitted condition more accurately conveys the intent. "Loop forever", vs. "Loop while true is true". A clever compiler wil
by sgtnoodle 4y ago
The semantics of the for loop with an omitted condition more accurately conveys the intent. "Loop forever", vs. "Loop while true is true". A clever compiler will optimize it to the same machine code, but conceptually the while loop is more complex. It requires understanding what a tautology is, for example.
- timmb 4y agoI’m used to seeing for(;;) in C code but I disagree that it’s conceptually similar - the opposite actually. The for() syntax is already inconsistent with three expressions being interpreted as statement;guard-expression;statement. 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.
- sgtnoodle 4y agoYou're arguing syntax, I'm arguing semantics. When the intent is to have the program loop unconditionally, omitting a condition seems more appropriate than providing a tautological condition. 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.
- JonChesterfield 4y agoEven a really stupid compiler is going to map for(;;) and while(1) to the same thing. An unconditional back branch at the end of the block. Anything else would be more work.