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

Re: for loop 'bad math expression'



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.

-- 
Mikael Magnusson




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