Search code examples
c++cpostfix-operator

Why this code returns 0 & 1?


I know postfix operator increment value after using the variable. But in this case, is it a valid statement? since it seems like i am modifying a variable after its return statement.

#include <iostream>

using namespace std;

int val = 0;

int foo()
{
        return val++;
}

int main()
{
        cout<<foo();
        cout<<endl<<val;
}

Any elaboration will be helpful.


Solution

  • Saying that return val++ first returns val and then increments it is not quite true. The expression val++ increments the value of val, but evaluates to the old value of val.

    You can think of the postfix ++ as a function that uses a helper variable to hold the old value:

    int temp = val; // save old value to temp
    ++val;          // increment actual value
    return temp;    // evaluate to old value