bug-bash
[Top][All Lists]
Advanced

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

Re: Arithmetic expression: evaluation order bug


From: Chet Ramey
Subject: Re: Arithmetic expression: evaluation order bug
Date: Wed, 4 Jan 2023 10:21:26 -0500
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0) Gecko/20100101 Thunderbird/102.6.0

On 12/29/22 12:23 PM, Steffen Nurpmeso wrote:
Hello.

   Name:         bash
   Path:         /usr/ports/core
   Version:      5.2.15
   Release:      1 >
   $ i=10 j=20;echo $(( i += j += i += j ));echo $i,$j
   60
   60,50

This has already been beaten pretty much to death, so I'll just explain
how the bash expression evaluator works on this.

It's all operator precedence and associativity. += has lower precedence
than other operators and associates right-to-left. So var += expr looks up
`var' and retrieves its value, evaluates `expr', performs the operation,
and returns the value of `var' after the assignment.

That means this will parse like

i += (j += i += j)
i += (j += (i += j))
i += (j += (i += (j)))

and evaluate like

j -> 20
i += 20 -> i = 30 (intermediate result)
j += 30 -> j = 50
i += 50 -> i = 60 (uses initial value of i)

because you evaluate by fetching the value of the lhs first, saving it
and its value because you know you need it, evaluating the rhs, then
performing the operation on the saved value and assigning the result.

In the end, though, this is completely undefined behavior.

--
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet@case.edu    http://tiswww.cwru.edu/~chet/




reply via email to

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