octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: undefined compound chaining behavior


From: Daniel J Sebald
Subject: Re: undefined compound chaining behavior
Date: Mon, 09 Jun 2014 10:40:15 -0500
User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.24) Gecko/20111108 Fedora/3.1.16-1.fc14 Thunderbird/3.1.16

On 06/06/2014 01:12 PM, Rik wrote:
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".

Also, I'm not so sure the right-to-left evaluation makes sense because this is both an operation and assignment in one. Explicitly applying associativity using parentheses, think about:

octave-cli:7> a=1;a+=(a+=4)
a =  10

which makes sense, I guess. The parentheses are evaluated with an inherent assignment and serves as an input to the proceeding add/assign. But the following makes no sense:

octave-cli:8> a=1;(a+=a)+=4
parse error:

  invalid left hand side of assignment

a=1;(a+=a)+=4

and the parser gives up, appropriately. The first parentheses is an evaluation (i.e., quantity) and the add/assign can only apply to a variable, not a quantity.

Dan




reply via email to

[Prev in Thread] Current Thread [Next in Thread]