How do pass variable pass by reference in C?

Viewed 79

I want to display x,y,z value with pass by reference method how to do that?

  • What is the pass by value-result?

      void f1(int x, int y, int z){
          x = y + z;
          y = z + 1;
          printf("x: %d y:  %d z: %d",x,y,z);
      }
    
      int main(int argc, char *argv[]) {
          int r = 5;
          int t = 10;
          int k = 15;
          f1(r, t, t + k);
          printf(" r : %d t:  %d k : %d",r,t,k);
      }
    

Any help is appreciated.

1 Answers

It's just a case of using indirection, which in C means pointers:

// Declare any arguments that are mutated as pointers
void f1(int* x, int* y, int z) {
  *x = *y + z;
  *y = z + 1;
  printf("x: %d y:  %d z: %d", *x, *y, z);
}

int main(int argc, char *argv[]) {
  int r = 5;
  int t = 10;
  int k = 15;
  f1(&r, &t, t + k);
  printf(" r : %d t:  %d k : %d",r,t,k);
}

Note that in order to use pointers you must have something to point to. t + k is not of those things. Arguably z is not mutated as an argument, so it could be a plain int.

As far as order of operations goes, t + k is computed and assigned as the argument before mutations occur.

Related