[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: increment & decrement error when variable is 0
From: |
felix |
Subject: |
Re: increment & decrement error when variable is 0 |
Date: |
Wed, 25 Nov 2020 10:37:45 +0100 |
User-agent: |
Mutt/1.10.1 (2018-07-13) |
On Mon, Nov 23, 2020 at 05:20:22PM -0500, Greg Wooledge wrote:
> On Mon, Nov 23, 2020 at 07:36:29PM +0000, Jetzer, Bill wrote:
>...
> Exercises 1 and 2 apply directly...
>From man bash:
((expression))
The expression is evaluated according to the rules described be‐
low under ARITHMETIC EVALUATION. If the value of the expression
is non-zero, the return status is 0; otherwise the return status
is 1. This is exactly equivalent to let "expression".
So little modified test/demo:
for ((i=-100; i<100; i++)) ;do
x=$i
((v = --x ,v)) || echo "err code $? on --x going from $i to $x -> $v"
x=$i
((v = x-- ,v)) || echo "err code $? on x-- going from $i to $x -> $v"
x=$i
((v = ++x ,v)) || echo "err code $? on ++x going from $i to $x -> $v"
x=$i
((v = x++ ,v)) || echo "err code $? on x++ going from $i to $x -> $v"
done
Will render near same output:
err code 1 on ++x going from -1 to 0 -> 0
err code 1 on x-- going from 0 to -1 -> 0
err code 1 on x++ going from 0 to 1 -> 0
err code 1 on --x going from 1 to 0 -> 0
Where *when the value of the expression is zero, the return status is 1*.
Difference between ((x--)) and ((--x)) is only usefull when *using* this
variable simultaneously while decrementing them (for assignment, testing,
or printing):
i=10;while ((i));do echo $i;((i--));done
and
i=10;while ((i));do echo $i;((--i));done
will do same result.
But
i=10;while ((i));do echo $((i--));done # return 10 to 1
i=10;while ((i));do echo $((--i));done # print 9 to 0
or
i=10;while ((i--));do echo $i;done # print 9 to 0
i=10;while ((--i));do echo $i;done # print 9 to 1 (exit at 0 before print)
--
Félix Hauri - <felix@f-hauri.ch> - http://www.f-hauri.ch