1
#include <stdio.h>

void change(int *num1, int *num2) {
    *num1 = 50; 
    ++*num2++;
}

int main() {
    int num1 = 1; int num2 = 2;
    char bye[] = "Bye World!";
    printf("Hello World!\n%s\n", &bye);
    printf("num1: %d, num2: %d\n", num1, num2);
    change(&num1, &num2);
    printf("num1: %d, num2: %d\n", num1, num2);
    getchar();
    return 0;

}

Looking at the following code, why is the output:

Hello World! Bye world!
num1: 1, num2: 2
num1: 50, num2: 3

instead of

Hello World! Bye world!
num1: 1, num2: 2
num1: 50, num2: 4

Under change(), shouldn't num2 still be incremented by one after the pre-increment? I imagine this is what happens in memory:

  • num2 = 2 (before call to change())
  • num2 = 3 (the pre-increment)
  • num2 = 3 (value returned before the post-increment)
  • num2 = 4 (the post-increment)
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

2

Under change() shouldn't num2 still be incremented by one after the pre-increment?

No, it shouldn't. There are two reasons for it:

  • Pre-increment increments the value; post-increment increments the pointer — in ++*num2++ the first ++ applies to whatever is pointed to by num2, but the second one applies to num2 itself due to precedence rules: post-increment have higher precedence than pre-increment and dereference.
  • If you set precedence by parentheses, one expression cannot modify the same value twice — this is a rule explained in Q&A on sequence points.
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0
++*num2++;

means the same as:

++(*(num2++));

i.e. it increments *num2 and num2 once each. It does not increment *num2 twice.

user253751
  • 57,427
  • 7
  • 48
  • 90