Passing by reference in C

后端 未结 17 2218
梦如初夏
梦如初夏 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: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
    

提交回复
热议问题