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

Re: arithmetic operator precedence



On Tue, Jun 17, 2008 at 03:02:46PM +0200, Vincent Lefevre wrote:
[...]
> It is unspecified. So, the shell is right to choose how it sees it.
> 
> > If $a contains an integer constant such as -3, then as per
> > POSIX, $((a * 3)) should be the same as $(($a * 3)), that is
> > $((-3 * 3)).
> 
> No, POSIX does not say that. It happens to be the same thing here
> just because of the properties of *, but you can't deduce anything
> for extensions.

It says $((x)) is meant to be the same as $(($x)) which I
understand as any occurrance of a variable name (other than $-,
$?, $0... obviously) in $((...)) should be the same as if the $
was not ommited (when $x contains an integer constant).

That's a recent addition to the text. Only recent versions of
ash (BSD shs) support that for instance, which is why it has
been recommanded for a while to write it $(($x + 1)) instead of
$((x + 1)) in POSIX scripts. And I still use x=$(($x + 1)).

For newer ashes, $((x + 1)) is now accepted and note that you do
get an error in ash if $x is not an integer constant.

> And in practice, shells don't treat $((a * 3)) and
> $(($a * 3)) in the same way:
> 
> vin:~> a="1 + 1"
> vin:~> echo $((a * 3))
> 6
> vin:~> echo $(($a * 3))
> 4

But here, $a doesn't contain an integer constant, that's out of
the scope of POSIX.

> 
> > If we extend that to the non-POSIX **, that would be:
> > 
> > a=-3; $((a ** 2)) should be the same as $((-3 ** 2)).
> 
> No, if we extend POSIX in an intuitive way (see above), $((a ** 2))
> should be the same as $(((-3) ** 2)), hence 9. So, no problem with
> $((-3**2)) being -9.
[...]

No, POSIX does say that $((a ** 2)) is the same as $(($a ** 2))
because $a contains an integer constant, and that's $((-3**2)).

-- 
Stéphane



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