-4
int a{1};

while(a--){

cout<<"yes";}

Why does the console prints "yes", the value of while should be 0

  • Learn about `a--` versus `--a`. Search for prefix / postfix. [https://stackoverflow.com/questions/7031326/what-is-the-difference-between-prefix-and-postfix-operators](https://stackoverflow.com/questions/7031326/what-is-the-difference-between-prefix-and-postfix-operators) – drescherjm Apr 17 '22 at 16:21
  • Because `a` has been initialized with `1` and `a--` uses post decrement operator. – Jason Apr 17 '22 at 16:23

2 Answers2

1

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.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
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:

  1. decrements a so that the new value of a becomes 0.
  2. returns the old value of 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.

Jason
  • 36,170
  • 5
  • 26
  • 60