3

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.

Federico Baù
  • 6,013
  • 5
  • 30
  • 38
Serhat
  • 187
  • 1
  • 14

1 Answers1

5

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • thanks a lot. what is the pass by value-result with this code can you help me ? – Serhat Jan 14 '21 at 14:16
  • 1
    @Serhat: What trouble are you having finding the pass-by-value result? The code in the question passes by value. You can compile and execute it. When you do that, what result do you get? What else do you want from it? – Eric Postpischil Jan 14 '21 at 14:20
  • @EricPostpischil is that code block pass-by-value-result or pass-by-reference ? – Serhat Jan 14 '21 at 14:24
  • @EricPostpischil i ran this code it's running this code block is call by reference method , i want to write pass by value result method i don't know what is that ? – Serhat Jan 14 '21 at 14:31
  • "Pass by value result method" is not something we talk about in C. Do you mean "I want a function that returns a value"? If so then you need to switch from `void` to `int` or something that matches the type of value you're trying to return, and then `return` that thing. Like `return z + 1`. If you're not mutating the arguments, pointers are not necessary. – tadman Jan 14 '21 at 14:35
  • As C does not have true references, when we say "reference" in C we mean "pointer". Everything in C is pass by value, where "references" are values that happen to be pointers to other values, giving the effect of a reference. – tadman Jan 14 '21 at 14:37