'Why does the console prints yes statement? [duplicate]
int a{1};
while(a--){
cout<<"yes";}
Why does the console prints "yes", the value of while should be 0
Solution 1:[1]
The variable a has been initialized with value 1. Moreover, the expression a-- uses postfix-decrement operator. So the expression a-- has 2 effects:
- decrements
aso that the new value ofabecomes0. - returns the old value of
awhich was1.
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
