+ 1
Explain please
how is the output of this program= 4. a=3; b=2; b=a++; cout <<++b;
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.
+ 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;