[Edu-sig] Pass by Reference

John Posner jjposner at snet.net
Sat May 17 14:19:35 CEST 2008


> Here is a simple program that calls a function with two 
> parameters, one called by value, the other by reference.  
> f(int a, int *b) { 
>     a += 1;   // modifies a local variable 
>    *b += 10;  // modifies the caller's variable }
> main() {
>   int x = 0; 
>   f(x, &x);   // pass the value and the pointer 
>   printf("x = %d\n", x);
> }
> // output is x = 10

Passing "x" twice in the same function call is distracting, IMHO. Try this
rewrite.
[ Also, more comments, please. I'm a tech writer by trade. :-) ]   -John

----------------
f(int a, int *b) { 
    a += 1;   /* modifies a local variable */
   *b += 12;  /* modifies the caller's variable */
}

main() {
  int x = 5; 
  int y = 30; 

  /* pass value of x, reference to y */
  f(x, &y);

  /* show results */
  printf("x = %d\n", x);
  printf("y = %d\n", y);
}

program output:

x = 5
y = 42
----------------



More information about the Edu-sig mailing list