Email List: Xaustin-group-lX
[All Lists]

Re: shell, arithmetic expansion and integer constants

To: austin-group-l@xxxxxxxxxxxxx
Subject: Re: shell, arithmetic expansion and integer constants
From: David Korn <dgk@xxxxxxxxxxxxxxxx>
Date: Tue, 17 Jun 2008 10:41:25 -0400
Subject: Re: shell, arithmetic expansion and integer constants
--------

> Concerning arithmetic expansion, POSIX says[*]:
> 
>   If the expression is invalid, the expansion fails and the shell
>   shall write a message to standard error indicating the failure.
> 
> [*] 
>http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_
> 02_06_04
> 
> But it doesn't seem to say anything if a variable contains an
> invalid value. It doesn't either say what values are regarded as
> valid (this is OK, but see below). Some values are required to
> be recognized ("Only the decimal-constant, octal-constant, and
> hexadecimal-constant constants specified in the ISO C standard,
> Section 6.4.4.1 are required to be recognized as constants."),
> but note that this doesn't even include negative integers.
> 
> What I'm thinking of is something like the following:
> 
> $ x="1+"
> $ echo $((x))
> sh: 1+: syntax error: operand expected (error token is "+")
> 
> i.e. the expression $((x)) is valid, but not the value of x.
> 
> Also, POSIX says:
> 
>   If the shell variable x contains a value that forms a valid integer
>   constant, then the arithmetic expansions "$((x))" and "$(($x))"
>   shall return the same value.
> 
> but it also explicitly says that a real-floating type can be used
> instead of signed long, and I think that the equivalence between
> "$((x))" and "$(($x))" should be required even through extensions.
> 
> So, to summarize:
> 
> Shouldn't "valid integer constant" be replaced by "valid constant",
> and say that if the value is invalid then the shell shall write a
> message to standard error indicating the failure?
> 
> Shouldn't POSIX require that negative integers are recognized (I'd say
> that the format should follow more or less what is described under the
> printf utility) and say that other valid forms are not specified?
> 
> An implementation could regard other forms as valid values, e.g.
> "1+1", so that the following would work in such an implementation:
> 
> $ x="1+1"
> $ echo $((x))
> 2
> $ echo $((x*2))
> 4
> 
> (the value 4 being required, 3 would be incorrect).
> 
> Any comment?
> 

As far as I am concerned, the less said about how a variable name
is mapped into a numerical value the better.

Some existing implementations already have typed variables and
the mapping between $x and the numerical value of x might
be very complex.

Consider an implementation that allows variables to be of type date.
The string value could be the same as the 'date' output and
the numerical value might be the time since the epoch.

David Korn
dgk@research.att.com

<Prev in Thread] Current Thread [Next in Thread>