Increment / Decrement Operator Behavior

simendsjo simendsjo at gmail.com
Mon Jun 4 13:08:56 PDT 2012


On Mon, 04 Jun 2012 20:57:11 +0200, simendsjo <simendsjo at gmail.com> wrote:

> On Mon, 04 Jun 2012 20:36:14 +0200, Xinok <xinok at live.com> wrote:
>
>> The increment and decrement operators are highly dependent on operator  
>> precedence and associativity. If the actions are performed in a  
>> different order than the developer presumed, it could cause unexpected  
>> behavior.
>>
>> I had a simple idea to change the behavior of this operator. It works  
>> for the postfix operators but not prefix. Take the following code:
>>
>> size_t i = 5;
>> writeln(i--, i--, i--);
>>
>> As of now, this writes "543". With my idea, instead it would write,  
>> "555". Under the hood, the compiler would rewrite the code as:
>>
>> size_t i = 5;
>> writeln(i, i, i);
>> --i;
>> --i;
>> --i;
>>
>> It decrements the variable after the current statement. While not the  
>> norm, this behavior is at least predictable. For non-static variables,  
>> such as array elements, the compiler could store a temporary reference  
>> to the variable so it can decrement it afterwards.
>>
>> I'm not actually proposing we actually make this change. I simply  
>> thought it was a nifty idea worth sharing.
>
> If I ever saw a construct like that, I would certainly test how that  
> works, then rewrite it.
> I wouldn't find it natural with the new behavior either. I would expect  
> "543" or "345".
> How often do you come across code like that? I think it's an  
> anti-pattern, and shouldn't be encouraged even if it was easier to  
> understand.

Oh, and what should writeln(i++, ++i, ++i, i++) do?

It is messy whatever the logic implementation.


More information about the Digitalmars-d mailing list