Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returning variable by reference?

Tags:

c++

In C++,

function() = 10;

Works if function returns a variable by reference, right?

Would someone please elaborate on this in detail?

like image 805
Mohit Jain Avatar asked Nov 27 '22 23:11

Mohit Jain


2 Answers

Consider this piece of code first

int *function();
...
*function() = 10;

Looks similar, isn't it? In this example, function returns a pointer to int, and you can use it in the above way by applying a unary * operator to it.

Now, in this particular context you can think of references as "pointers in disguise". I.e. reference is a "pointer", except that you don't need to apply the * operator to it

int &function();
...
function() = 10;

In general, it is not a very good idea to equate references to pointers, but for this particular explanation it works very well.

like image 101
AnT Avatar answered Dec 18 '22 06:12

AnT


Consider the following code, MyFunction returns a pointer to an int, and you set a value to the int.

int  *i;
i = MyFunction();
*i = 10;

Are you with me so far?

Now shorten that to

*(MyFunction()) = 10;

It does exactly the same thing as the first code block.

You can look at a reference as just a pointer that's always dereferenced. So if my function returned a reference - not a pointer - to an int the frist code block would become

int  &i;
i = MyFunction();
i = 10;

and the second would become

MyFunction() = 10;

You still with me?

like image 35
Binary Worrier Avatar answered Dec 18 '22 05:12

Binary Worrier