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. Commented Jul 22, 2012 at 21:43
  • act like normal? have you tried af(v); af(v);? Commented 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. Commented Jul 22, 2012 at 21:44
  • One link: codepad.org/1jTOscE8 Commented 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.

Sign up to request clarification or add additional context in comments.

Comments

24

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 Comments

"The & means that the function accepts the address"... ummm... no...
Just pointing out void main.
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.
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....)
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?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.