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

Re: arithmetic operator precedence



On Thu, Jun 19, 2008 at 06:00:24PM +0200, Vincent Lefevre wrote:
> 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.

I'm under the impression your misunderstand the purpose of
POSIX. POSIX is a tool to help people write portable
applications (when it comes to shells, that means _scripts_).

You cannot write z=$(( x <op> y ))

in a POSIX script, because the result is unspecified.

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

is specified (with the conditions I detailed).

If in your script, you make sure $x and $y are integer constants
(as in [-+]?(0[xX][a-fA-F0-9]+|0[0-7]+|[1-9][0-9]*)), then it
will work as expected.

If $x and $y are valid arithmetic expressions that may not be
integer constants as described above, then you need:

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

But I wouldn't do such things in a script.

My example was about $x and $y being the result of arithmetic
expansions.


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

POSIX is not about a theoretical implementation. It's the
specification of an API or a language if you like.

Just like the C spec doesn't specify a theoretical compiler, but
a language. Of course, someone who wants to design a C compiler
must refer to that spec, but the main target of that spec is
people writing C code.

-- 
Stéphane



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