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

Re: arithmetic operator precedence



On 2008-06-17 13:46:07 +0100, Stephane Chazelas wrote:
> On Tue, Jun 17, 2008 at 02:35:51PM +0200, Vincent Lefevre wrote:
> [...]
> > But POSIX does not say that variable expansion should be performed
> > before the arithmetic expression (at least in th way you think).
> > If POSIX said so, then with a="1 + 1", $((a * 3)) would give
> > $((1 + 1 * 3)) after variable expansion (without being able to make
> > the difference with $((1 + 1 * 3)) written directly), then 5 after
> > arithmetic expansion. But neither zsh nor bash behaves in that way.
> [...]
> 
> $((a * 3)) is unspecified as per POSIX if $a doesn't contain an
> integer constant. That was my point.

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. 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

> 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.

> So, if a future version of POSIX adds a **, it is bound to
> specify it as $((-3 ** 2)) == 9 if it wants to keep consistant.

Choosing -9 is also consistent (see above).

-- 
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