0

int a=2; int b=3; while(b--)++a; cout<<a; Why does this code print 5?

26th Jul 2016, 2:12 PM
jigoku_tenshi
4 Answers
+ 5
for any integral values not equal to zero inside the while condition, the conditions holds good and it prints out,but when b-- becomes zero the condition becomes false and the final value of a that is 5 is printed due to the following iterations 1st iteration b remains 3(post increments) and a becomes 3(pre increment) 2nd iteration b becomes 2 and a becomes 4 3rd iteration b becomes 1 and a becomes 5 ------- ------- -------- -------- -------- AND NOW FINALLY B BECOMES ZERO CONDITION BECOMES FALSE AND THE FINAL VALUE OF A =5 IS PRINTED OUT :)
26th Jul 2016, 3:09 PM
Aditya Pai
Aditya Pai - avatar
0
In short, any int that is greater than one is considered true. If it is 0 or less, it is considered false. As we know, while(true) is an infinite loop, while(false) will not run. Inside of the parameters we have --b, it is important to know that this is done BEFORE the while loop checks if the condition is true or not. So as soon as b reaches 0, a will be the value in which b started with. On the next iliteration, b-- is done again (hence why b = -1 if you print it out), and sees that it evaluates to false, thus the loop ends. Bit of a silly loop to be honest and got my head in a muddle, but I learnt something new today, thanks :)
26th Jul 2016, 3:15 PM
Cohen Creber
Cohen Creber - avatar
0
Cohen: number 0 is false, every others true.
27th Jul 2016, 4:45 PM
ddrodoric
0
So why when b = -1, the while loop stops? -1 would be true? This question confused me but I'm learning at the same time so it's great.
27th Jul 2016, 4:55 PM
Cohen Creber
Cohen Creber - avatar