views:

197

answers:

5

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?

+12  A: 

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 */
GMan
+4  A: 

C does not support pass by reference. You'll need C++ to do it the way it is written, or modify into

int locate(char *name, int *s, int *i)

and pass pointers to the second and third parameter variables.

wallyk
A: 

Your code would work fine in C++. Unless your code needs to be pure-C, just compile it using a C++ compiler instead.

dmazzoni
I think this is an awful suggestion. If the OP wants to write C, they should write C, and compile it with a C compiler. "Switch languages" is not an answer to the OP's problem (pass-by-reference in C).
Chris Lutz
Yeah I can't switch languages. However, I did learn about references in C++. I just assumed that C had them too.
Phenom
+8  A: 

C has no reference variables but you can consider reference as const pointer to data so ,

Make const pointer to data like this so that pointer cant point to other data but data being pointed by it can be changed.

int  locate (char *name,  int  * const s, int * const i)
Ashish
+1 for const pointer suggestion
Qberticus
+1  A: 

You can't do this in c. c doesn't have reference, you can use pointer instead.

Raymond