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

Re: arithmetic operator precedence



On Mon, Jun 16, 2008 at 02:42:11PM +0100, Peter Stephenson wrote:
> On Mon, 16 Jun 2008 10:07:26 +0200
> Vincent Lefevre <vincent@xxxxxxxxxx> wrote:
> > Speaking of precedence, the following one is nasty:
> > 
> > vin% zsh -c 'echo $((-3**2))'
> > 9 
> > vin% bash -c 'echo $((-3**2))'
> > 9
> > vin% ksh93 -c 'echo $((-3**2))'
> > 9
> > 
> > IMHO these shells should be fixed to give -9, i.e. ** should have
> > the precedence over the unary -, like conventional math writing.
> 
> That's an interesting point for C_PRECEDENCES since I was trying to get
> it behave as much as possible like Perl.  What does anyone else think?
[...]

It's at least consistent with other shells and bc at the moment:

~$ bash -c 'echo $((-2**2))'
4
~$ zsh -c 'echo $((-2**2))'
4
~$ ksh93 -c 'echo $((-2**2))'
4
~$ echo '-2 ^ 2' | bc
4

bc is one place where POSIX specifies the precedence of
unary-minus vs power:
http://www.opengroup.org/onlinepubs/009695399/utilities/bc.html
minus has higher precedence than ^ which I have to say is more
intuitive to me.

Having said that:

~$ perl -le 'print -2 ** 2'
-4
~$ python -c 'print -2 ** 2'
-4
~$ ruby -e 'print -2 ** 2'
-4%
~$ gawk 'BEGIN {print -2 ** 2}'
-4

TCL has pow(x, y) instead of an operator.

-- 
Stéphane



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