+ 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.

22nd May 2017, 12:05 AM
Sohn Jmith
Sohn Jmith - avatar
3 odpowiedzi
+ 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..
22nd May 2017, 12:13 AM
jay
jay - avatar
+ 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
22nd May 2017, 12:13 AM
Károly György Tamás
Károly György Tamás - avatar
+ 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
22nd May 2017, 12:09 AM
AMR ELSAWY
AMR ELSAWY - avatar