Why no (auto foo = bar) in while loops?

Timon Gehr timon.gehr at gmx.ch
Wed Aug 24 12:54:06 PDT 2011


On 08/24/2011 09:36 PM, Jonathan M Davis wrote:
> On Wednesday, August 24, 2011 21:29:23 Timon Gehr wrote:
>> On 08/24/2011 09:21 PM, Andrej Mitrovic wrote:
>>> On 8/24/11, Timon Gehr<timon.gehr at gmx.ch>   wrote:
>>>> it is usually faster
>>>> in debug mode
>>>
>>> Huh.. How come?
>>
>> Well, not notably faster, but many compilers will emit something in the
>> lines of
>>
>> mov eax, 1
>> test eax
>> jnz beginning_of_loop
>>
>> if no optimizer is run,
>>
>> whereas most get
>>
>> for(;;){}
>>
>> as
>>
>> jmp beginning_of_loop
>>
>> even in debug mode.
>
> Optimizations aside, I would always argue that while(true) should be used
> rather than for(;;). I find for(;;) to be ugly personally and would argue that
> while(true) better captures what you're actually doing. A loop with no
> condition at all is horrible IMHO. It seems completely inconsistent to me that
> the language would allow you to have a for loop without a condition.
>
> Regardless of that, however, I would fully expect that if there is a difference
> in code between the two in debug mode (which there shouldn't be IMHO, but
> compilers don't always do what makes the most sense - especially in debug
> mode) that the difference would be drowned by the contents of the loop and
> wouldn't matter at all. But even if it did, I'd generally argue that coding in
> a certain way just because it was slightly faster in debug mode but had zero
> impact in release mode is not a good idea unless all of the considerations are
> equal. And I'd definitely argue that while(true) is better than for(;;) from an
> aesthetic point of view at minimum, so they definitely aren't equal.
>
> In any case, that's my take on it.
>
> - Jonathan M Davis

Well, it is consistent in that you can leave out the other parts in for 
too. (but those are statements, and you can almost everywhere write an 
empty statement, while there exist no empty expressions)

As to while(true) vs for(;;), in my point of view, it is the other way 
round, because how it is compiled in debug mode is really how the 
semantics of the language are: look at the condition, and if it is true, 
loop another time, if it is false, break. If you want an infinite loop, 
why bother having to write a condition to evaluate? Imho for(;;){} 
captures the meaning better than while(true){}. for(;;){} means, loop 
unconditionally (which proves insight in what it is actually doing), and 
while(true){} means 'loop until true is false', which is imo ugly for 
obvious reasons.

That is my way of thinking about aesthetics in programming.



More information about the Digitalmars-d-learn mailing list