+ 1

Explain please

how is the output of this program= 4. a=3; b=2; b=a++; cout <<++b;

16th Nov 2016, 12:52 PM
stephen haokip
stephen haokip - avatar
2 Answers
+ 1
in the third line, b=a++. this is post increment, which means first 'use' the value and then update it. So 'a' is used to copy to b first. So b equals 3. then 'a' gets updated to 4. in the last line ++b. which is pre increment. which means first update the value and then use. b was 3 at this point. So b gets updated to 4 and then printed. output is 4.
16th Nov 2016, 12:56 PM
P Sandesh Baliga
P Sandesh Baliga - avatar
+ 1
a++ means you do something before you add. ++b means you add first before you do something. so in your case, you assign the original value of a (3) to b, then you add 1 to the value of a. b = a++ is the same as b = a; a = a + 1; then for the last line, you add 1 first to the value of b. that is why the answer is 4. cout<< ++b is the same as b = b + 1; cout<< b;
16th Nov 2016, 1:10 PM
Junjie Gono
Junjie Gono - avatar