What is the "&" operator in the return type of a function?

Jun 6, 2014 at 8:35pm
Hello. I stacked at the point & operator. I don't know so many things about & reference operator and i'm searching on the web.

My question is that to put reference operator in a return type of a function is technically possible. But what does it mean literally? I don't imagine what does this mean ? It seems like below

1
2
3
4
int & f()
{
 ....
}

Could you show me please some differerent code snippets of & operators for this purpose of using?
Thanks in advance
Last edited on Jun 6, 2014 at 8:38pm
Jun 6, 2014 at 8:59pm
It returns reference to int. That means if you change returned value, original will change too.
For example operator[] in standard container vector returns reference to the stored type making things like v[5] = 10; possible.
Example:
1
2
3
4
5
6
7
8
9
10
int& get(int* array, int i, int j, int width)
{
    int index = i * width + j;
    return array[index];
}
//...
int arr[10] = { 0 };
get(arr, 0, 1, 5) = 1;
get(arr, 1, 2, 5) = 2;
//arr now [0, 1, 0, 0, 0, 0, 0, 2, 0, 0] 
Jun 6, 2014 at 9:02pm
There is no such thing as a reference operator.

int& f() is a function which returns a reference to int.

The version of operator<< that is overloaded for std::ostream returns a reference to std::ostream which enables one to chain calls such as:

std::cout << 1 << ' ' << 2 << ' ' << 3 << '\n' ;
instead of doing:
1
2
3
4
5
6
 std::cout << 1;
 std::cout << ' ';
 std::cout << 2;
 std::cout << ' ';
 std::cout << 3;
 std::cout << '\n';


On the other hand, there are not many non-contrived use cases for returning a reference to a simple type like int. (Edit: Although, MiiNiPaa has supplied one.)


Could you show me please some differerent code snippets of & operators for this purpose of using?

Again, & is not an operator in this context. You can think of it as part of the type.
Last edited on Jun 6, 2014 at 9:04pm
Topic archived. No new replies allowed.