Passing by reference in C

2018-12-31 05:05发布

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 

17条回答
谁念西风独自凉
2楼-- · 2018-12-31 05:42

You're not passing an int by reference, you're passing a pointer-to-an-int by value. Different syntax, same meaning.

查看更多
栀子花@的思念
3楼-- · 2018-12-31 05:45

In C, to pass by reference you use the address-of operator & which should be used against a variable, but in your case, since you have used the pointer variable p, you do not need to prefix it with the address-of operator. It would have been true if you used &i as the parameter: f(&i).

You can also add this, to dereference p and see how that value matches i:

printf("p=%d \n",*p);
查看更多
大哥的爱人
4楼-- · 2018-12-31 05:45

'Pass by reference' (by using pointers) has been in C from the beginning. Why do you think it's not?

查看更多
梦醉为红颜
5楼-- · 2018-12-31 05:46

In C everything is pass-by-value. The use of pointers gives us the illusion that we are passing by reference because the value of the variable changes. However, if you were to print out the address of the pointer variable, you will see that it doesn't get affected. A copy of the value of the address is passed-in to the function. Below is a snippet illustrating that.

void add_number(int *a) {
    *a = *a + 2;
}

int main(int argc, char *argv[]) {
   int a = 2;

   printf("before pass by reference, a == %i\n", a);
   add_number(&a);
   printf("after  pass by reference, a == %i\n", a);

   printf("before pass by reference, a == %p\n", &a);
   add_number(&a);
   printf("after  pass by reference, a == %p\n", &a);

}

before pass by reference, a == 2
after  pass by reference, a == 4
before pass by reference, a == 0x7fff5cf417ec
after  pass by reference, a == 0x7fff5cf417ec
查看更多
何处买醉
6楼-- · 2018-12-31 05:47

In C, Pass-by-reference is simulated by passing the address of a variable (a pointer) and dereferencing that address within the function to read or write the actual variable. This will be referred to as "C style pass-by-reference."

Source: www-cs-students.stanford.edu

查看更多
登录 后发表回答