+ 1
int a=3; int b=2; b=a++; cout<<++b; Can someone explain how we arrived at 4?
I just don't understand how this works. int a=3; a=3, okay int b=2; b=2, got it b=a++; b (which equals 2) is equal to a (which equals 3) +1, so 2=3+1? what? cout<<++b; How the hecc did we arrive at 4? I think I need the postfix and prefix functions explained to me simpler.
3 Answers
+ 4
++variable does addition before statement is evaluated (prefix)
variable++ does addtion after statement is evaluated (postfix)
Edit: A simple way to understand these terms is to break up the words into their literal meanings.
pre(latin:before)-fix(well, fix) = fix the calculation before we do anything.
post(after)- etc... etc..
+ 3
b=a++ means:
b = a; # first âbâ get the value of âaâ
a = a + 1; # âaâ increased after the assignment
cout<<++b means:
b = b + 1; # âbâ increased before the cout
cout<<b; # print to the screen
+ 1
b = a++;
it assigns a into b so b = 3 then increment a
cout << ++b;
it first increment b so b = 4 then print b. Therefore, it prints 4