"a[++i] = i" vs "a[i] = ++i"
Timon Gehr
timon.gehr at gmx.ch
Tue Dec 24 08:15:15 PST 2013
On 12/24/2013 01:48 AM, H. S. Teoh wrote:
> Agreed. Note that introducing assignment into the mix may not help
> matters, but complicate them even more. For example:
>
> int x=1, y=0;
> writeln((y = ++x) + (++y--) * (x=y)); // what does this print?
> ...
'y-- is not an lvalue'.
Assuming we add parens as follows:
int x=1, y=0;
writeln((y = ++x) + ((++y)--) * (x=y));
We should get 8 according to strict left to right evaluation rules.
Furthermore, we should have the value 2 stored in both x and y.
> Or worse yet:
>
> int func1(int x) { ... }
> int func2(int x) { ... }
> int func3(int x) { ... }
>
> int function(int)[] funcptrs = [ &func1, &func2, &func3 ];
>
> int x=0, y=0;
> y += funcptrs[++x--](y = --x++); // what does this do?
>
'x-- is not an lvalue'
'x++ is not an lvalue'
Assuming we run the following code instead:
int func1(int x) { return 1*x; }
int func2(int x) { return 2*x; }
int func3(int x) { return 3*x; }
int function(int)[] funcptrs = [ &func1, &func2, &func3 ];
int x=0, y=0;
y += funcptrs[(++x)--](y = (--x)++)
We should be left in a state where x contains 0 and y contains -2
according to strict left to right evaluation rules.
> The only place I can see where you'd even*want* to write code like this
> is in an entry to the IOCCC. Make it refuse to compile, I say.
I don't think it makes sense to add some arbitrary rules to the compiler
implementation just to ban some code that nobody writes anyway and
potentially some perfectly fine code as well.
More information about the Digitalmars-d-learn
mailing list