V
V
Vladimir Korshunov2022-01-11 14:01:40
C++ / C#
Vladimir Korshunov, 2022-01-11 14:01:40

What is the purpose of returning a value by reference?

I used to think that returning a value by reference differs from returning a value by a pointer in that in the first case it would not be necessary to dereference the pointer, but apparently this is not so. I wrote this example:

#include <iostream>

int& func(int &a)
{
    std::cout << &a << "\n\n";
    return a;
}

int main()
{
    int a;
    int b;
    b = func(a);
    std::cout << &b << "\n\n";
    std::cout << &a << "\n\n";
    return 0;
}

I thought that three identical addresses would be displayed, but this is not so. If you return by value, the result will be identical. What is the purpose of returning a value by reference?
If we return a pointer to a variable, then in the caller it has the same address (we returned it) and information at this address, but the pointer address will already be different. If we return a variable by reference, then the address of this variable in the caller is already different, only the information remains the same. Why and why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2022-01-11
@GashhLab

b = func(a);
This is where you took the reference returned by func and copied the value into b. So the &b below will give you the address of the variable b, not what you wanted.
Returning references is convenient when you need to return a value without copying and it always exists. Because a function that returns a pointer can, in general, return nullptr as well. On mind, it would be necessary to check this pointer before dereferencing. But links - they always point somewhere.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question