0

These are (some) of the ways to define a function in C++ (depending on what the function should do):

type f_name (type par) {/*...*/}
type f_name(type& par) {/*...*/}

where the first one passes as argument a copy of par to the function, whereas the second one passes a reference to the variable par, which means that if something 'happens' to the variable, it will be reflected in the variable itself.

My confusion is with the following definition

type& f_name(type& par) {/*...*/}

I don't understand what the & means in the return type of the function. Also when should I and shouldn't I use it?

EDIT: I would appreciate if the answer came with a representative example

hal
  • 105
  • 1
  • 3
  • 1
    It means the same thing as it does for the parameter: the function returns a reference to some object, rather than a copy of that object. – Igor Tandetnik Sep 07 '20 at 16:09
  • 2
    It's a *return by reference*. It's rare to see in a non-member function as it allows the caller to modify whatever the reference is referring to. It's quite common when overloading operators – Bathsheba Sep 07 '20 at 16:09
  • Ok, but passing the variable as a reference effectively achieves that, i.e. that the passing parameter is modified. What does it mean that -on top of the reference to the parameter- the function returns a reference to any object that returns...? – hal Sep 07 '20 at 16:16
  • One thing to note, returning reference to variable with atomic storage duration from function is UB. – pvc Sep 07 '20 at 16:19
  • In general it could happen that the function is updating a particular variable in the global scope including, but not limited to, creating new heap space for it. In this case it makes sense to return an address (or a pointer). You might find [this question](https://stackoverflow.com/questions/29309414/cpp-using-or-to-return-address) interesting. – Sarwagya Sep 07 '20 at 16:19
  • Also, [this article](https://www.learncpp.com/cpp-tutorial/74a-returning-values-by-value-reference-and-address/) explains the use case difference of return by address and return by reference – Sarwagya Sep 07 '20 at 16:23
  • 1
    @pvc: Not quite - the reference might also be passed into the function as a parameter. Some of the C++ standard library functions work like this, so I'm not mentioning this just to be picky. – Bathsheba Sep 07 '20 at 16:27
  • @Bathsheba, your right, thank you. – pvc Sep 07 '20 at 16:32

0 Answers0