I'm trying to use pass by reference in C so that the function can modify the values of the parameters passed to it. This is the function signature:
int locate(char *name, int &s, int &i)
However when I try to compile it I get this error that refers specifically to the above line:
error: expected ‘;’, ‘,’ or ‘)’ before '&' token
If I remove the '&' the program will compile, but it will not function correctly, obviously. What's wrong here? How can I make call by reference work?
Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.
Pass by Reference A reference parameter "refers" to the original data in the calling function. Thus any changes made to the parameter are ALSO MADE TO THE ORIGINAL variable. Arrays are always pass by reference in C.
"Passing by value" means that you pass the actual value of the variable into the function. So, in your example, it would pass the value 9. "Passing by reference" means that you pass the variable itself into the function (not just the value). So, in your example, it would pass an integer object with the value of 9.
C does not have references. You need to pass a pointer to the variable you wish to modify:
int locate(char *name, int *s, int *i)
{
/* ... */
*s = 123;
*i = 456;
}
int s = 0;
int i = 0;
locate("GMan", &s, &i);
/* s & i have been modified */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With