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
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]
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.