Passing by reference in C

aks picture aks · Feb 9, 2010 · Viewed 380k times · Source

If C does not support passing a variable by reference, why does this work?

#include <stdio.h>

void f(int *j) {
  (*j)++;
}

int main() {
  int i = 20;
  int *p = &i;
  f(p);
  printf("i = %d\n", i);

  return 0;
}

Output:

$ gcc -std=c99 test.c
$ a.exe
i = 21 

Answer

tvanfosson picture tvanfosson · Feb 9, 2010

Because you're passing the value of the pointer to the method and then dereferencing it to get the integer that is pointed to.