C++ operation too confusing?

102 views Asked by At

I can't seem to understand this operation. What is the output of the following code? I've tried interpreting why b has two different values one as b=1+2 and the other as b=2, since a++ should equal to a=1+a ,then the cout is asking for ++b, which one should it should equal to, b=2-1 or b=3-1?

int a=3;
int b=2;
b=a++;
cout<<++b;

I know the answer to this question is 4. But i can't get my head around it.

2

There are 2 answers

1
R Sahu On BEST ANSWER

But i can't get my head around it.

When that happens you can try to simplify the statements/expressions.


Due to the use of the post-increment operator,

b = a++;

is equivalent to:

b = a;
a = a+1;

Due to the use of the pre-increment operator,

cout<<++b;

is equivalent to:

b = b+1;
cout << b;

Hope it makes sense now.

0
Sam Varshavchik On

why b has two different values

b does not have two different values. b, a, and everything else, always has one value, at any given time. It might have different values at different times, but it always has just one value, at a given time.

Since a is 3, then:

b=a++;

Sets b to 3, since the post-increment operation modifies the value of a after the value of a is used in the expression.

cout<<++b;

This outputs 4, because the pre-increment operation modifies the value of b before it is used in the expression. Since b starts out with 3, it gets incremented to 4, then used in the expression.