+ 7

Why the final value of b is 0?

Can someone explain why this code outputs 0 (b equals zero)? int main() { int b = 0; b = b++; cout << b; return 0; }

6th Nov 2016, 2:54 PM
Wojciech Duda
Wojciech Duda - avatar
12 Antworten
+ 6
what happens when you x = x++; is (assume u r passing x to a function) function(x){ xOLD = x; x = x+1; return xOLD; } so, x = x++; becomes x = (store old value of x --> do (x+1)--> return old value of x) and hence, x = x; (or x = xOLD) For other variables it works perfectly, y = x++; becomes, y = (store OLD value of x --> do (x+1) --> return OLD value of x); and thus, y=x;(or y = xOLD) hope this clarifies your problem, thumbs up if it does👍
6th Nov 2016, 3:26 PM
Paul Kabira
Paul Kabira - avatar
+ 5
congrats wojciech on 500 challenge victories...amazing
13th Nov 2016, 11:10 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 4
@gowtham The single line b = b++; becomes temp = b; b = b+1; b = temp; for others, eg y = b++; expands to; temp = b; b = b+1; y = temp;
6th Nov 2016, 4:28 PM
Paul Kabira
Paul Kabira - avatar
+ 4
It should be case 1{ int b = 0; b = b++; //b=0 } case 2{ int b = 0; b = ++b; //b=1 } case 3{ int a = 0; int b = 0; a = b++; //a=0 and b=1 } case 4{ int a = 0; int b = 0; a = ++b; //a=1 and b=1 }
7th Nov 2016, 5:51 AM
Valeria Ferretti
Valeria Ferretti - avatar
+ 3
ok, but isn't this single line equal to two lines: b = b; b++ ? It's a bit confusing for me. That is why I try to avoid such constructions in my code.
6th Nov 2016, 3:00 PM
Wojciech Duda
Wojciech Duda - avatar
+ 3
@paul kabira then in your function how would you access the new "x" as u said it returns xOLD variable value.
26th Dec 2016, 3:51 PM
Rishabh Agrawal
Rishabh Agrawal - avatar
+ 2
b++ return b so 0 so b = 0
6th Nov 2016, 2:56 PM
TheNewHEROBRINE
TheNewHEROBRINE - avatar
+ 1
when u write b = ++b; the result be : 1
6th Nov 2016, 3:05 PM
Amine Karimi
Amine Karimi - avatar
+ 1
Read the course. b++ returns the currwnt value of b, THEN adds 1
8th Nov 2016, 8:58 AM
Seckar
Seckar - avatar
+ 1
it is post increment operation so the value of variable is updated afterwards
15th Nov 2016, 7:56 AM
Krishna Sharma
Krishna Sharma - avatar
+ 1
prefix and postfix operator ++b is prefix...it will increment the value then use it. but in case of b++. first it will use old value then increment it. so b= b++ . cout<< b gives 0
22nd Nov 2016, 10:33 PM
rohit kumar
rohit kumar - avatar
+ 1
since it is a post increment operator ,the previous value of b that is '0' assigned to b again then it will get incremented... so the value of b remains same... therefore output is 0
30th Jun 2018, 8:43 AM
Anjali Kesavarapu