PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] How do pass variable pass by reference in C?

 July 05, 2022     arguments, c, function, pass-by-reference, variables     No comments   

Issue

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.


Solution

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.



Answered By - tadman
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing