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?

Community
  • 1
  • 1
vico
  • 17,051
  • 45
  • 159
  • 315

2 Answers2

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
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;
}
cegfault
  • 6,442
  • 3
  • 27
  • 49
  • 10
    "The & means that the function accepts the address"... ummm... no... – Luchian Grigore Jul 22 '12 at 21:48
  • Just pointing out [void main](http://stroustrup.com/bs_faq2.html#void-main). – chris Jul 22 '12 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`. – Johannes Schaub - litb Jul 22 '12 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 '12 at 21:53
  • That is, conceptually, it's passing a reference to the object instead of making a copy and passing the value but how it *actually* works with the gcc compiler is to make a copy of the memory address and pass it. – cegfault Jul 22 '12 at 21:54
  • 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? – Luchian Grigore Jul 22 '12 at 21:59