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?
This question is related to
c++
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
.
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;
}
Source: Stackoverflow.com