Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass by reference in C

Tags:

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?

like image 909
neuromancer Avatar asked Dec 17 '09 05:12

neuromancer


People also ask

What is pass by reference in C?

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.

What is pass by reference example?

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.

Does C have pass 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.

What is pass by value and 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.


1 Answers

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 */
like image 63
GManNickG Avatar answered Oct 24 '22 04:10

GManNickG