Search code examples
c++post-increment

What happened in the function convert(&m)?


Here is the code:

int convert(int* a) {
    return (*a)++;
}

int main(){
    int m = 56;
    int n = convert(&m);
    cout << m << endl;
    m = convert(&m);
    cout << m << endl;
    return 0;
}

Why is the answer m=57 instead of m=58 after m=convert(&m)?


Solution

  • The second call increments m to 58, but it returns the original value (57) due to the use of the post-increment ++ operator. That original value is then assigned back to m, overwriting the incremented value. The net effect is that m is unchanged.

    You can verify this by adding some printouts to see the exact values in play:

    int convert(int* a) {
        std::cout << "*a was " << *a << std::endl;
        int ret = (*a)++;
        std::cout << "*a is now " << *a << std::endl;
        std::cout << "return value is " << ret << std::endl;
        return ret;
    }
    

    m = convert(&m); prints:

    *a was 57
    *a is now 58
    return value is 57