0
I want to understand this code
a=3; b=2; b=a++; cout<< b++; Why this gives 4 it shouldn’t be 5??
30 Respostas
+ 8
a=3;
b=2;
b=a++;//b=3 and a=4
cout<<b++;//first print value of b means 3 and then incremented by 1 means b=4
cout<<b++;//print 4 but value of b is 5
Because it is postfix(b++) operator
+ 5
Ipang I was wondering same, the output must be 3 neither 4 nor 5.
+ 5
b=a++ it is mean add a value to b and add +1 to a after
Naw b=3 ,a=4
after that copy b++ mean 3+1
+ 4
I tested the code in Code Playground and got 3 as output (as I expected).
+ 4
Hello_World Your explanation is correct but since there is only single cout statement so the final output will be 3
+ 3
Its answer is 3 not 4 or 5
+ 2
nAutAxH AhmAd
We'll have to wait for the OP to confirm that I guess : )
+ 2
nAutAxH AhmAd I know ,Just written to understand
+ 2
Buddy i think the output should be 3 not 4 and not 5. Let see how??
a=3;
b=2;
b=a++;//it is post increment so, first assign then increment i.e. b=3 and a=4
cout<< b++;//now same it is also post increment i.e. first it will print the value of b i.e. b=3 and then increment it by 1.
+ 2
consider this "b = a++ " -> as "b = a ; a++ ". It works like this,just a matter of prefix and postfix.
+ 2
Instead of cout <<b++;
Write cout<<++b; for Ans=5
+ 1
It should be 3.
+ 1
This code gives 3 as output.
If you will print a then it should gived 4 as output.
+ 1
cout<<b++ means first cout and then b++
if cout << ++b means first b+=1 and then cout b
+ 1
a++, while it does increment a, returns the value of it before - not after - it was incremented. The snippet "a = 999; b = a++;" therefore sets b to 999, not 1000. If you want it the other way, use ++a instead, which returns the real, incremented value of a.
+ 1
Try this way. You'll get 5 as output.
#include <iostream>
using namespace std;
int main(){
int a=3;
int b=2;
b += a;
cout<< b++;
}
+ 1
b = 2. Then b = 3 and on the next line it will be 4. Now both a and b are 4. On the cout, b is 4, but if you use it again, b will be 5.
b++ increments the value AFTER the line ran.
+ 1
because -> a++ = a+1
++a = 1+a
so if you entered :
b = a++ means b= a and a= a+1
but if you entered :
b= ++a means b=1+a and a=a
+ 1
b=a++ this means b is 3 because of the postfix so when you run the code b is increased by 1