Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: arithmetic operator precedence



On 2008-06-19 10:54:54 +0100, Stephane Chazelas wrote:
> With all the existing operators, one can do
> 
> x=$(( some-expression ))
> y=$(( some-other-expression ))
> z=$(( $x <op> $y ))
> 
> and it's OK whatever some-expression and some-other-expression
> and <op> as long as they are POSIX.

This is not guaranteed to work. Indeed POSIX allows constants other
than the "canonical" ones to be recognized. With such constants,
you can get wrong results. Whether such constants can occur for some
reason is another matter. In *practice*, it is safer to write:

  z=$(( ($x) <op> ($y) ))

and even safer to write:

  z=$(( x <op> y ))

though it may not work in non-POSIX shells.

> The syntax above is the only one you can write in a POSIX
> script, and POSIX guarantees it to work at the moment.
> 
> If you change ** so that it has  higher precedence than the
> unary minus, you break that harmony.

That's a completely stupid reason. In practice, many shells recognize
other constants, such as "1+1" (this is allowed by POSIX), even more
than those which support **. For instance:

$ a='1+1'; echo $((a * 2)); echo $((3**2))
4
pdksh: 3**2: unexpected `*'

and:

$ a='1+1'; echo $((a * 2)); echo $((3**2))
4
posh: 3**2: unexpected `*'

So, writing z=$(( $x <op> $y )) will not work anyway.

Shells should be designed to work *in practice* (and do what the
user expects to get), not to work specifically on theoretical
implementations that will never exist.

-- 
Vincent Lefèvre <vincent@xxxxxxxxxx> - Web: <http://www.vinc17.org/>
100% accessible validated (X)HTML - Blog: <http://www.vinc17.org/blog/>
Work: CR INRIA - computer arithmetic / Arenaire project (LIP, ENS-Lyon)



Messages sorted by: Reverse Date, Date, Thread, Author