Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why b doesn't change always its value when I run ((a++)) && ((b++)) in bash?

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?

like image 316
Radu Rădeanu Avatar asked Dec 13 '25 23:12

Radu Rădeanu


2 Answers

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.

like image 183
Stuart Caie Avatar answered Dec 15 '25 20:12

Stuart Caie


&& 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.

like image 32
Almo Avatar answered Dec 15 '25 19:12

Almo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!