Passing by reference in C

后端 未结 17 2225
梦如初夏
梦如初夏 2020-11-21 23:26

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

#include 

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

int main() {
  int i = 20;         


        
相关标签:
17条回答
  • 2020-11-21 23:31

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

    0 讨论(0)
  • 2020-11-21 23:32

    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
    
    0 讨论(0)
  • 2020-11-21 23:34

    p is a pointer variable. Its value is the address of i. When you call f, you pass the value of p, which is the address of i.

    0 讨论(0)
  • 2020-11-21 23:35

    No pass-by-reference in C, but p "refers" to i, and you pass p by value.

    0 讨论(0)
  • 2020-11-21 23:35

    Because you're passing a pointer(memory address) to the variable p into the function f. In other words you are passing a pointer not a reference.

    0 讨论(0)
  • 2020-11-21 23:36

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

    0 讨论(0)
提交回复
热议问题