tohnotakaki tohnotakaki - 1 month ago 16
C Question

Inner workings of call by reference

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


Answer

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.