45

Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
What's the meaning of * and & when applied to variable names?

Trying to understand meaning of "&" in this situation

void af(int& g)
{
    g++;
    cout<<g;
}

If you call this function and pass variable name - it will act the same like normal void(int g). I know, when you write &g that means you are passing address of variable g. But what does it means in this sample?

4
  • You can find that information in a detailed, already answered form here.
    – chris
    Jul 22, 2012 at 21:43
  • act like normal? have you tried af(v); af(v);? Jul 22, 2012 at 21:44
  • 9
    It's a reference, and if you don't know what it is I strongly recommend you to read a C++ book. Jul 22, 2012 at 21:44
  • One link: codepad.org/1jTOscE8 Jul 22, 2012 at 21:46

2 Answers 2

37

It means you're passing the variable by reference.

In fact, in a declaration of a type, it means reference, just like:

int x = 42;
int& y = x;

declares a reference to x, called y.

23

The & means that the function accepts the address (or reference) to a variable, instead of the value of the variable.

For example, note the difference between this:

void af(int& g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

And this (without the &):

void af(int g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}
6
  • 10
    "The & means that the function accepts the address"... ummm... no... Jul 22, 2012 at 21:48
  • Just pointing out void main.
    – chris
    Jul 22, 2012 at 21:48
  • void main() is fine. Nothing wrong with this. Of course I assume that this is incomplete code (he misses "#include" too), so there will be a namespace lulz { ... } around his void main. Jul 22, 2012 at 21:50
  • updated main to int main to make Chris happy ;) And @LuchianGrigore: actually, yes, the function does accept the address. If you use printf("%x",&g); inside and outside of of af(), you will find the values are different (at least when I compile with gcc...). The compiler is actually making a copy of the memory address and passing that to the function; there IS another object on the stack, believe it or not (again, at least this is happening for me in gcc....)
    – cegfault
    Jul 22, 2012 at 21:53
  • 2
    so you're saying you can call the function as af(&g), right? Since &g is the address of g, and you say that af accepts the address of a variable? Jul 22, 2012 at 21:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.