What kind of variable declaration is "char&"?

What kind of variable declaration is it when you put the "&" sign right after specifying the type of a variable?

In source code it usually looks something like this:

1
2
3
...
void function_name(char& achar, ...);
...


I noticed that it mostly occurs inside parameter definition of any function.
At first I thought that it had to do with the "address-of" operator "&", but isn't it used more like this?:

1
2
3
4
...
int * x;
x = &a; //Where "a" is a previously declared variable with or without any value in it's memory block
...
Last edited on
This has nothing to do with the "address of" operator. It just happens to be the same symbol.


It makes 'achar' a reference to a char.

References are sort of like aliases for another variable. For example:

1
2
3
4
int a = 0;
int& b = a;  // b IS a

b = 5;  // same as saying a = 5 


When in the context of a function parameter, it's like passing the variable to the function:

1
2
3
4
5
6
7
8
9
10
11
12
void func(int& foo)
{
  foo += 5;
}

int main()
{
  int a = 3;
  func( a );  // this will actually modify 'a'

  cout << a;  // outputs '8'
}
Now I see.

Thanks Disch.
Topic archived. No new replies allowed.