-1

For the code below why are the variables x,y,s pass-by-value while only z is pass-by-reference.

void foo(int* a, int* b, int& c, int d) {
  *a = *a + 1;
  b = b + 1;
  c = c + 1;
  d = d + 1;
}

int main() {
 int x = 0, y = 5, z = 10, s = 20;
 foo(&x, &y, z, s);
 cout << x << “, ” << y << “, ” << z <<“, ” << s <<endl;
 return 0;
 }
Sammy2000
  • 15
  • 6
  • 1
    Look at the types of `foo`'s parameters. Which ones are references? – molbdnilo Nov 20 '19 at 08:03
  • Oh, it is because in the void foo, only c has &? – Sammy2000 Nov 20 '19 at 08:05
  • so does it not matter that in the main, foo(&x, &y) is calling by reference? – Sammy2000 Nov 20 '19 at 08:06
  • 1
    Yes, only `c` is a reference. (But `foo` is not "a void"; it is a function and `void` is its return type.) – molbdnilo Nov 20 '19 at 08:06
  • 5
    `&` means "reference" only in a type. When it's a unary operator in an expression, like in `&x`, it is the "address-of" operator and is entirely unrelated to references. You're not passing `x` by reference, you're passing `&x` - which is an `int*` - by value. – molbdnilo Nov 20 '19 at 08:07
  • The re-use of the symbol `&` for declaring references is unfortunate because (1) it violates the C paradigm that a declaration is syntactically identical to an expression with the declared variable and (2) because of the confusion that arises from the semantically close "address-of" and "reference", to which you are not the first to fall victim. References are kind-of redundant with pointers anyway except that operator overloading is more natural because one does not have to pass pointers. – Peter - Reinstate Monica Nov 20 '19 at 08:26
  • It is the function that determines whether an argument is passed by reference. The caller can't force a function to accept something by reference. In your code `&x`, `&y`, and `s` are all passed by value. This means any changes to their values in the function are invisible to the caller. `&x` and `&y` (in `main()`) are pointers, so the function can change what those pointers point at i.e. it can change, as far as `main()` is concerned, `x` and `y` but not `&x` or `&y`. `s` is passed by reference, so can be changed directly by the function. – Peter Nov 20 '19 at 09:19

1 Answers1

0

in function foo() a,and b are pointers ie, they will take address of the variable and in function call addresses of x and y are passed. But c takes reference to the argument provided . You can see C program examples here on geeksforgeeks

Yasir
  • 332
  • 2
  • 9