Let's take the following example from my terminal:
$ a=0 && b=1
$ echo $a $b
0 1
$ # Everything OK
$ ((a++)) && ((b++))
$ echo $a $b
1 1
$ # What? Why only a changed its value and b no?
$ ((a++)) && ((b++))
$ echo $a $b
2 2
$ # Now the value of b has changed...
Can someone to make me understand why this is happening?
a++ is post-increment, i.e. the increment happens after the value is tested.
The test on a fails because a is zero at the time it is tested.
&& is the logical AND operator. If its first argument is false, it doesn't bother evaluating the second. This is called "short-circuiting" and saves processing time.
Since ++ is post increment, if a is zero when evaluating ((a++)) && ((b++)), it evaluates a first, gets zero (which is false), adds 1 to a, then quits due to the short-circuit without evaluating the second part. So b does not get incremented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With