postincrement behaviour (differences between dmd and gdc)

Lionello Lunesu lionello at lunesu.remove.com
Wed Jan 24 22:43:23 PST 2007


"Derek Parnell" <derek at psych.ward> wrote in message 
news:sh2qs4ffr1mg$.1tm119rzt8yyw$.dlg at 40tude.net...
> On Wed, 24 Jan 2007 21:31:44 +0100, Nicolai Waniek wrote:
>
>> Hello again,
>>
>> I have a huge arguing going on with a friend of mine, which behaviour of
>> x++ is the right one. This has in fact to do with D, so read on :)
>>
>> This is our example application:
>>
>> int x = 5;
>> x = x++;
>> x = x++;
>> print(x);
>>
>>
>> I argue: the result printed is 7.
>> He argues: the result printed is 5.
>>
>> the "++" operator is defined as: "returns the value and then increments
>> it by 1". so I guess, the execution should be as follows:
>
> I think that DMD is correct. The result should be 5.
>
> Based on the definition above, I think that the example is equivalent to
> ...
>
>  int x = 5;
>  int temp;
>
>  // x = x++;
>  temp = x;  // temp is now 5
>  x = x + 1; // x is now 6
>  x = temp;  // x is now 5
>
>  // x = x++;
>  temp = x;  // temp is now 5
>  x = x + 1; // x is now 6
>  x = temp;  // x is now 5
>
> The key phrase is "returns the value and then increments" which I take it
> to mean that it returns the value of the variable that it had prior to it
> being incremented.

I agree. Take this code:

int f( int i ) { return i; }//nop

int x=5;
x = f(x++);
assert(x==5);
x = f(x++);
assert(x==5);

L. 





More information about the Digitalmars-d mailing list