int a{1};
while(a--){
cout<<"yes";}
Why does the console prints "yes", the value of while should be 0
int a{1};
while(a--){
cout<<"yes";}
Why does the console prints "yes", the value of while should be 0
a--
(it's called using a postfix operator) means first inspect the value of a
, then decrement. I.e. the value of the expression a--
is the value of a
before decrement.
Therefore in the first while
iteration it is still 1.
If you used --a
instead (which is a called using a prefix operator), you would not have seen the "yes" printed,
because --a
means first decrement, then inspect the resulting value.
The variable a
has been initialized with value 1
. Moreover, the expression a--
uses postfix-decrement operator. So the expression a--
has 2 effects:
a
so that the new value of a
becomes 0
.a
which was 1
.Thus the condition holds true and the while block is entered one time.
On the other hand, if you were to use --a
, then the while block will not be executed because --a
uses prefix-decrement operator which returns the decremented value(0
in your case) instead of returning the old value. So the condition will not be satisfied and the while block is never entered.