+ 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; }
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👍
+ 5
congrats wojciech on 500 challenge victories...amazing
+ 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;
+ 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
}
+ 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.
+ 3
@paul kabira
then in your function how would you access the new "x" as u said it returns xOLD variable value.
+ 2
b++ return b so 0 so b = 0
+ 1
when u write b = ++b;
the result be : 1
+ 1
Read the course.
b++ returns the currwnt value of b, THEN adds 1
+ 1
it is post increment operation so the value of variable is updated afterwards
+ 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
+ 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