Increment / Decrement Operator Behavior
Xinok
xinok at live.com
Mon Jun 4 11:36:14 PDT 2012
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.
More information about the Digitalmars-d
mailing list