Passing by reference in C

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

    Your example works because you are passing the address of your variable to a function that manipulates its value with the dereference operator.

    While C does not support reference data types, you can still simulate passing-by-reference by explicitly passing pointer values, as in your example.

    The C++ reference data type is less powerful but considered safer than the pointer type inherited from C. This would be your example, adapted to use C++ references:

    void f(int &j) {
      j++;
    }
    
    int main() {
      int i = 20;
      f(i);
      printf("i = %d\n", i);
    
      return 0;
    }
    

提交回复
热议问题