0

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)?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
KingBob
  • 5
  • 3
  • 2
    Fix this by not doing really strange things inside functions. _Either_ return the new value _or_ adjust the parameter. Don't do both at once. – Lundin Mar 08 '21 at 11:10

1 Answers1

3

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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578