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

Documenting $(( foo )) as similar to $(( ($foo) ))



On Sun, Feb 4, 2024, at 9:43 PM, Mikael Magnusson wrote:
> On 2/5/24, Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx> wrote:
>> On Sun, Feb 4, 2024 at 12:49 PM Lawrence Velázquez <larryv@xxxxxxx> wrote:
>>>
>>> I'm not sure if the zsh manual spells this behavior out explicitly,
>>> but bash and ksh share it.
>>
>> "Arithmetic Evaluation" says (pretty far down after the discussion of
>> operators):
>> ===
>> Named parameters and subscripted arrays can be referenced by name within
>> an arithmetic expression without using the parameter expansion syntax.
>> For example,
>>      ((val2 = val1 * 2))
>> assigns twice the value of $val1 to the parameter named val2.
>>
>> =(and later)=
>>
>> Scalar variables can hold integer or floating point values at different
>> times; there is no memory of the numeric type in this case.
>>
>> If a variable is first assigned in a numeric context without previously
>> being declared, it will be implicitly typed as integer or float and
>> retain that type either until the type is explicitly changed or until
>> the end of the scope.  This can have unforeseen consequences.
>> ===
>>
>> It doesn't explicitly say how "the value of $val1" is determined, but
>> if it were expanded with $val1 you'd get the whole text string which
>> would then be interpreted as arithmetic, so expanding without the $
>> works the same.
>
> This last bit is not 100% true, a parameter will combine into its
> context with $ but not without:
> % a=3+2
> % echo $(( 5 / a )) # 5/5
> 1
> % echo $(( 5 / $a )) # 5/3 + 2
> 3
>
> I think effectively you can think of foo as ($foo), at least in all
> cases I can think of to try.

I just noticed that Bart added the following text to zshmisc(1):

	If the expansion of $val1 is text rather than a number,
	then when val1 is referenced that text is itself evaluated
	as a math expression as if surrounded by parentheses
	`($val1)'.

I assumed that Mikael's comparison of foo with ($foo) was meant to
be an analogy, so I didn't nitpick it at the time, but I worry that
this addition to the documentation could be misconstrued as implying
that code like this ought to be valid:

	% foo='1) + (2'
	% print $((foo))
	zsh: bad math expression: unexpected ')'

...just because this is valid (if ill-advised):

	% print $((($foo)))
	3


-- 
vq




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