Decrement operator

I don't why this confuses me but can someone tell me what the output of this code would be.

1
2
3
4
int count=3;
while (--count)
     cout<<count<<' ';
cout<<endl;
Last edited on
2 1


--count decreases the count variable first before being used.
ok thank you!
operators such as -- or ++ are different than + or - (such as count-1 or count+1). + and - will change the value temporarily, whereas -- and ++ will change the value of the variable permanently.

Also, there's something else going on here.

while(--count)

will behave differently than

while(count--)

So...

1
2
3
4
int count=3;
while (count--)
     cout<<count<<' ';
cout<<endl;


would actually come out to read:

2
1
0


This is because of where the -- was placed. Placing it after the variable will decrease the variable's value only after the while loop's check has been made on the variable. So, the first run through the while loop will see count as equaling 3 and continue on through the loop, while quickly stopping to decrease count by 1. The next time through it will see count as 2, and the third time through it will see count as 1, thereby running the loop a third time. After the third iteration however, count becomes 0, which is why you'd see it output as I showed above.
++x = increment then return.

x++ = return then increment.

Just read it from left to right. You return the value when you hit the variable, and you increment/decrement when you hit the operator.

That's how it made sense to me at least.
Topic archived. No new replies allowed.