bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Logical operators in arithmetic evaluation: documentation vs impleme


From: Pierre Gaston
Subject: Re: Logical operators in arithmetic evaluation: documentation vs implementation
Date: Thu, 18 Apr 2013 17:36:47 +0300

On Thu, Apr 18, 2013 at 5:36 PM, Pierre Gaston <pierre.gaston@gmail.com>wrote:

>
>
>
> On Thu, Apr 18, 2013 at 12:59 PM, andras@coolbox.se <andras@coolbox.se>wrote:
>
>> The ARITHMETIC EVALUATION section of the man page claims equivalence with
>> C for all the operators, but in reality bash does not perform short circuit
>> evaluation, which implies that the logical operators do NOT produce the
>> same results as in C.
>> Try these, for example:
>>
>> f () {
>> # echo "$@" >&2
>>     local n=$1
>>     echo $((0 < n ? n * $(f $((n-1))) : 1))
>> }
>>
>> or
>>
>> g() {
>> # echo "$@" >&2
>>     local a=$1 b=$2
>>     echo $((0 == b ? a : $(g b $((a%b)))))
>> }
>>
>> Note that && and || are affected the same way, and the side effect is not
>> due solely to recursion.
>>
>> $ echo $((1 || $(echo + >&2 && echo 0)))
>>
>> $ echo $((0 && $(echo + >&2 && echo 1)))
>>
>> The results are correct, but the side effects are NOT the same as in C.
>>
>> This may all be fine and as intended, but in that case the documentation
>> feels somewhat misleading.
>>
>> Best,
>>
>> --@;
>>
>
>
> Expansions are not part of the arithmetic evaluation and are done before.
> So your $( )  and $(( )) inside the outer $(( ))  are done before the
> arithmetic evaluation starts.
>
> For the evaluation bash does short-circuit:
> $ n=0;echo $(( n?++n:n))
> 0
> $ n=1;echo $(( n?++n:n))
> 2
> $ n=0;echo $(( 1 && ++nn));echo $n
> 1
> 0
>
> sorry the last example is bogus better:
$ n=0;echo $(( 1 || ++n));echo $n
1
0


reply via email to

[Prev in Thread] Current Thread [Next in Thread]