Passing by reference in C

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

    What you are doing is pass by value not pass by reference. Because you are sending the value of a variable 'p' to the function 'f' (in main as f(p);)

    The same program in C with pass by reference will look like,(!!!this program gives 2 errors as pass by reference is not supported in C)

    #include 
    
    void f(int &j) {    //j is reference variable to i same as int &j = i
      j++;
    }
    
    int main() {
      int i = 20;
      f(i);
      printf("i = %d\n", i);
    
      return 0;
    }
    

    Output:-

    3:12: error: expected ';', ',' or ')' before '&' token
                 void f(int &j);
                            ^
    9:3:  warning: implicit declaration of function 'f'
                   f(a);
                   ^
    

提交回复
热议问题