On 06/06/2014 08:06 AM, address@hidden wrote:
Message: 5
Date: Fri, 6 Jun 2014 17:20:08 +0330
From: Hossein Sajjadi<address@hidden>
To: address@hidden
Subject: chaining compound assignment results in undefined behavior
Message-ID:
<address@hidden>
Content-Type: text/plain; charset=UTF-8
Hi
There is a problem with chaining compound assignment.
For example the expression a=1;a+=a+=4 will result 10.
I think such a behavior is borrowed from C language but this behavior
is known as "undefined behavior".
This issue have been resolven in Java.
Java language guarantees that the operands of operators appear
to be evaluated in a specific evaluation order , namely, from left to
right. ?15.7
Other specifications about evaluation of expressions are in
"The Java? Language Specification"
also this approach is followed by c# language
so result of above expression in Java is 6
I don't think we need to do anything here. First, code should
self-documenting and easy to understand. When I first looked at the
statement I couldn't figure out what the intent was, and so I'm not
surprised that the compiler also has a hard time deciding what to do. So,
I would suggest that rather than introduce complexities in to the parser,
the programmer should simply write what they mean.
If the programmer wants 6 as an answer, then code
a = 1; a += a; a+= 4
If the programmer wants 10 as an answer, then code
a = 1; a +=4; a += a
I tried the example in C++ and the result with the gcc compiler is 10 so
I'm perfectly happy to define the behavior that multiple in-place operators
are evaluated in a specific evaluation order which happens to be "right to
left".