Search code examples
c++operations

C++ operation too confusing?


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.


Solution

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