10.5 — Returning values by value, reference, and address

In the three previous lessons, you learned about passing arguments to functions by value, reference, and address. In this section, we’ll consider the issue of returning values back to the caller via all three methods.

As it turns out, returning values from a function to its caller by value, address, or reference works almost exactly the same way as passing arguments to a function does. All of the same upsides and downsides for each method are present. The primary difference between the two is simply that the direction of data flow is reversed. However, there is one more added bit of complexity -- because local variables in a function go out of scope and are destroyed when the function returns, we need to consider the effect of this on each return type.

Return by value

Return by value is the simplest and safest return type to use. When a value is returned by value, a copy of that value is returned to the caller. As with pass by value, you can return by value literals (e.g. 5), variables (e.g. x), or expressions (e.g. x+1), which makes return by value very flexible.

Another advantage of return by value is that you can return variables (or expressions) that involve local variables declared within the function without having to worry about scoping issues. Because the variables are evaluated before the function returns, and a copy of the value is returned to the caller, there are no problems when the function’s variable goes out of scope at the end of the function.

Return by value is the most appropriate when returning variables that were declared inside the function, or for returning function arguments that were passed by value. However, like pass by value, return by value is slow for structs and large classes.

When to use return by value:

  • When returning variables that were declared inside the function
  • When returning function arguments that were passed by value

When not to use return by value:

  • When returning a built-in array or pointer (use return by address)
  • When returning a large struct or class (use return by reference)

Return by address

Returning by address involves returning the address of a variable to the caller. Similar to pass by address, return by address can only return the address of a variable, not a literal or an expression (which don’t have addresses). Because return by address just copies an address from the function to the caller, return by address is fast.

However, return by address has one additional downside that return by value doesn’t -- if you try to return the address of a variable local to the function, your program will exhibit undefined behavior. Consider the following example:

As you can see here, value is destroyed just after its address is returned to the caller. The end result is that the caller ends up with the address of non-allocated memory (a dangling pointer), which will cause problems if used. This is a common mistake that new programmers make. Many newer compilers will give a warning (not an error) if the programmer tries to return a local variable by address -- however, there are quite a few ways to trick the compiler into letting you do something illegal without generating a warning, so the burden is on the programmer to ensure the pointer they are returning will point to a valid variable after the function returns.

Return by address was often used to return dynamically allocated memory to the caller:

This works because dynamically allocated memory does not go out of scope at the end of the block in which it is declared, so that memory will still exist when the address is returned back to the caller. Keeping track of manual allocations can be difficult. Separating the allocation and deletion into different functions makes it even harder to understand who’s responsible for deleting the resource or if the resource needs to be deleted at all. Smart pointers (covered later) and types that clean up after themselves should be used instead of manual allocations.

When to use return by address:

  • When returning dynamically allocated memory and you can’t use a type that handles allocations for you
  • When returning function arguments that were passed by address

When not to use return by address:

  • When returning variables that were declared inside the function or parameters that were passed by value (use return by value)
  • When returning a large struct or class that was passed by reference (use return by reference)

Return by reference

Similar to return by address, values returned by reference must be variables (you should not return a reference to a literal or an expression that resolves to a temporary value, as those will go out of scope at the end of the function and you’ll end up returning a dangling reference). When a variable is returned by reference, a reference to the variable is passed back to the caller. The caller can then use this reference to continue modifying the variable, which can be useful at times. Return by reference is also fast, which can be useful when returning structs and classes.

However, just like return by address, you should not return local variables by reference. Consider the following example:

In the above program, the program is returning a reference to a value that will be destroyed when the function returns. This would mean the caller receives a reference to garbage. Fortunately, your compiler will probably give you a warning or error if you try to do this.

Return by reference is typically used to return arguments passed by reference to the function back to the caller. In the following example, we return (by reference) an element of an array that was passed to our function by reference:

This prints:


When we call getElement(array, 10), getElement() returns a reference to the array element with index 10. main() then uses this reference to assign that element the value 5.

Although this is somewhat of a contrived example (because you can access array[10] directly), once you learn about classes you will find a lot more uses for returning values by reference.

When to use return by reference:

  • When returning a reference parameter
  • When returning a member of an object that was passed into the function by reference or address
  • When returning a large struct or class that will not be destroyed at the end of the function (e.g. one that was passed in by reference)

When not to use return by reference:

  • When returning variables that were declared inside the function or parameters that were passed by value (use return by value)
  • When returning a built-in array or pointer value (use return by address)

Mixing return references and values

Although a function may return a value or a reference, the caller may or may not assign the result to a variable or reference accordingly. Let’s look at what happens when we mix value and reference types.

In case A, we’re assigning a reference return value to a non-reference variable. Because giana isn’t a reference, the return value is copied into giana, as if returnByReference() had returned by value.

In case B, we’re trying to initialize reference ref with the copy of the return value returned by returnByValue(). However, because the value being returned doesn’t have an address (it’s an r-value), this will cause a compile error.

In case C, we’re trying to initialize const reference cref with the copy of the return value returned by returnByValue(). Because const references can bind to r-values, there’s no problem here. Normally, r-values expire at the end of the expression in which they are created -- however, when bound to a const reference, the lifetime of the r-value (in this case, the return value of the function) is extended to match the lifetime of the reference (in this case, cref)

Lifetime extension doesn’t save dangling references

Consider the following program:

In the above program, returnByReference() is returning a const reference to a value that will go out of scope when the function ends. This is normally a no-no, as it will result in a dangling reference. However, we also know that assigning a value to a const reference can extend the lifetime of that value. So which takes precedence here? Does 5 go out of scope first, or does ref extend the lifetime of 5?

The answer is that 5 goes out of scope first, then the reference to 5 is copied back to the caller, and then ref extends the lifetime of the now-dangling reference.

However, the following does work as expected:

In this case, the literal value 5 is first copied back into the scope of the caller (main), and then ref extends the lifetime of that copy.

Returning multiple values

C++ doesn’t contain a direct method for passing multiple values back to the caller. While you can sometimes restructure your code in such a way that you can pass back each data item separately (e.g. instead of having a single function return two values, have two functions each return a single value), this can be cumbersome and unintuitive.

Fortunately, there are several indirect methods that can be used.

As covered in lesson 10.3 -- Passing arguments by reference, out parameters provide one method for passing multiple bits of data back to the caller. We don’t recommend this method.

A second method involves using a data-only struct:

A third way (introduced in C++11) is to use std::tuple. A tuple is a sequence of elements that may be different types, where the type of each element must be explicitly specified.

Here’s an example that returns a tuple, and uses std::get to get the nth element of the tuple:

This works identically to the prior example.

You can also use std::tie to unpack the tuple into predefined variables, like so:

As of C++17, a structured binding declaration can be used to simplify splitting multiple returned values into separate variables:

Using a struct is a better option than a tuple if you’re using the struct in multiple places. However, for cases where you’re just packaging up these values to return and there would be no reuse from defining a new struct, a tuple is a bit cleaner since it doesn’t introduce a new user-defined data type.


Most of the time, return by value will be sufficient for your needs. It’s also the most flexible and safest way to return information to the caller. However, return by reference or address can also be useful, particularly when working with dynamically allocated classes or structs. When using return by reference or address, make sure you are not returning a reference to, or the address of, a variable that will go out of scope when the function returns!

Quiz time

Write function prototypes for each of the following functions. Use the most appropriate parameter and return types (by value, by address, or by reference), including use of const where appropriate.

1) A function named sumTo() that takes an integer parameter and returns the sum of all the numbers between 1 and the input number.

Show Solution

2) A function named printEmployeeName() that takes an Employee struct as input.

Show Solution

3) A function named minmax() that takes two integers as input and returns back to the caller the smaller and larger number in a std::pair. A std::pair works identical to a std::tuple but stores exactly two elements.

Show Solution

4) A function named getIndexOfLargestValue() that takes an integer array (as a std::vector), and returns the index of the largest element in the array.

Show Solution

5) A function named getElement() that takes an array of std::string (as a std::vector) and an index and returns the array element at that index (not a copy). Assume the index is valid, and the return value is const.

Show Solution

10.6 -- Inline functions
10.4 -- Passing arguments by address

301 comments to 10.5 — Returning values by value, reference, and address

  • Jim

    In this function you are returning an address, however inside the function x is multiplied by 2. You can't return both so are they multiplied and given a new address before being returned or what?

    • Alex

      You can't return the address of a local variable because that variable gets destroyed at the end of the function. In cases like this, return by value is really more appropriate. If you want to return something by address, you'll have to make sure the address you're returning isn't destroyed. You can do that in several ways: by returning the address of a static local variable (this has other downsides), or passing in another parameter by address that you can return (if the caller passes in a variable, it should still be valid when the function returns back to the caller). There may be other ways I'm not thinking of right now.

      But really this example just serves to show a simple point. Use the most appropriate return type for the situation, which is not return by address here. :)

  • Rob G.

    Hi Alex I learned more abt this dogged question I had above:

    Correct me if I am wrong but but the & in front of getElement tells the return value not to copy but pass the function return value by reference.

    I also created this in main:

    Do I need to delete this or will it automatically do so when main goeso ut of scope?

    • Alex

      You are correct about the & in the example above.

      As for the dynamic allocation, you need to delete it yourself. It will not be deleted when array goes out of scope.

    • Trevor

      When the program terminates (i.e. when main() goes out of scope), the operating system will clean up any undeleted dynamically allocated memory. Alex covered this in section 6.9.

  • Shiva


    Nice lesson yet again. I noticed that a function returning reference can be used both as an lvalue as well as an rvalue. I just tried the same with a function returning address (dereferencing the returned pointer), and it works fine:

    Is this proper? I want to know if my compiler is ‘helping me out’ to do something out of the standard.

    BTW I found out some typos as usual: :D

    > When returning an (a) built-in array or pointer (use return by address)
    > When we call getElement(array, 10), getElement() returns a reference to the element of the array inside array (<- what's this?) that has the index 10.

  • Rob G.

    Hi Alex,

    I took the initiative and wrote full programs (small) for each quiz above, but quiz 5 is in question below. I would recommend that you might encourage other students to do the same. It may "cement" what's learned better, apply what's learned to a situational context ridding some of the examples' isolation. It seems to be at least for me good practice and a lot of fun.

    Below is my function code for the last quiz. I don't understand fully the usage of & in front of the function name in your example; if I put an ampersand in front of array_element it seems to function correctly - I can access array_element back in main, the result array_element is changed at the source address, no copies. What am I misunderstanding here.

    Secondly can you please explain what the ampersand & does at the processor/memory level (the abridged version).

    • Alex

      In this context, we're using & to mean "reference to".

      When we have parameter "int array_element", that means the argument is going to be passed by value -- that is, whatever value we passed in will be copied into array_element. If we were to change array_element, the argument we passed in would not be changed, because array_element is a copy, and changing a copy doesn't change the original.

      However, if instead we have parameter "int &array_element", that means the argument is going to be passed by reference -- that is, whatever value we passed in, array_element will reference that argument. Any changes we make to array_element will be make to the argument as well. This is more efficient because no copies are made.

      Finally, when we use an ampersand as part of the return type, like this:

      That means this function is returning a reference to a const integer. Without the ampersand, this function would return a copy of the value at array[index] back to the caller. With the ampersand, we return a const reference to the actual array element. This allows the caller to access the array element (to print it, for example) without having to make a copy.

      • Rob G.

        I see my mistakes. First I thought arrays were passed implicitly by reference. Second I thought you could put the & in front of n_array: int * get_element (int * & n_array, int n_input_index, int &array_element) to reference it. Finally index - its passed in a return function without being referenced: is index copied?

  • Squalus

    Hi. Scope of variable defines where it is accessible and not where is created and destroyed. That is defined by duration of variable. So in this code:



    variable x goes out of scope (we can not access x directly after closing brace), but it is not destroyed (because it has static duration) and we can access it "indirectly" (through reference).
    BTW: Great tutorials.

  • Xhevo

    Dear Alex,
    besides greetings for your excellent explanations in this tutorial, can you explain, please, where is stored the value of "value" returned by the function, in the case of returning by value (and it works when the function is called(examp.1)), and where is stored the value of "&value" in the case of returning by address, and it does'n work when the function is called(examp.2). In both cases "value" is a local variable.
    Thanks a lot.

    [ examp. 1: this one works

    int doubleValue(int x)
        int value = x * 2;
        return value ; // A copy of value will be returned here
    } // value goes out of scope here

    examp.2: this one does'n works

    int* doubleValue(int x)
        int value = x * 2;
        return &value; // return nValue by address here
    } // value destroyed here

    • Alex

      Both of these functions work similarly. The difference is that in the top example, the value of variable value is copied to the caller. Because this is a copy, it doesn't matter what happens to local variable value after that point.

      In the bottom example, the address of local variable value is returned to the caller. Because local variable value then goes out of scope and is destroyed, this address becomes invalid.

  • Leonardo

    Hi Alex
    Greetings for your excellent blog. I have a question and i need help .

    I have a source code with three files. There is a file called MEDICAO.c . In this file there is a function called LER_VRMS ( ). In this file, there is a function called LER_VRMS ( ) , within this function, is called other function called LER_REG_24_BITS ( ) that is located inside another file.(DRIVER_ADE.c) After being executed, the return value should be assigned to the array [ ] .
    But that is not happening , I get a completely different value.

    Note: Array is declarared as global in file MEDIÇÃO.c


    • Alex

      Hi Leonardo. I can't even begin to guess what the problem might be from the information you've given me. My advice is use the debugger to step through your program and watch it execute. Put watches on the variables you're interested in and see where their values are getting changed.

  • Bede

    Hello Alex,
    In the solution of quiz 5, I think, there's a mistake now:

    It is supposed to return an array element (no copy), so IMHO it should be either:


  • Mike

    Hi Alex!

    In quiz 1, I think it should be "...and returns the sum of all the number_S_ between 1 and the input number".

    In quiz 4 and 5, isn't it safer to declare int *array as const?

    Thank you!

  • Mario

    Hi Alex,
    Congrats for the great tutorial. By far the best of C++ I've ever come across!

    One question, in the following code, that you have used when explaining 'return by address', after using the delete operator, shouldn't we set 'array' to be a null pointer? (array = 0)
    Otherwise wouldn't the pointer 'array' end up as a dangling pointer?:


  • eli

    Hi Alex,

    I still have a small missing part, that is related to assignments.
    On regular assignments a = b, b is copied and assigned to a.
    When we declare a as reference (SomeStruct &a = b), b i not copied.
    Now, what happens when instead of b we have a function?


    • Alex

      Good question.

      > SomeStruct& a = ByReferenceFunction(); // no copy is made

      a references the return value, no copy is made.

      > SomeStruct& b = ByValueFunction(); // a copy is made before function returns, and b now points to it

      This won't compile. You can't set a reference to a rvalue because the return value has no memory address. However, you could do this:

      In this case, the lifetime of the copied return value is extended to the lifetime of the const reference.

      > SomeStruct c = ByReferenceFunction(); // UNCLEAR: no copy is made by the function, but is the returned value copied to c?

      This returns a reference to some value, but because c is not a reference, a copy is made and placed in c. So this is essentially the same thing as not returning a reference.

      > SomeStruct d = ByValueFunction(); // UNCLEAR: a copy is made before function returns, but is it copied again before assigning it to d?

      No, the return value is copied into d.

  • Mr D

    Hi Alex,

    In this tutorial you seem to start doing something that you earlier (6.7) said we shouldn't do:

    But in this lesson:, the * next to int. And several other places in this tutorial.
    So me is getting confused, is there some special reason for this or.......

    • Alex

      Yes, there is a slight difference.

      In the case where we're declaring a variable, putting the asterisk next to the variable name helps us avoid this mistake:

      (IMO, C++ made a syntactical mistake here, they really should both be pointers to int, but that's not the case)

      However, with a function return value where there's only one return value:

      Makes it clear that the function is returning a value of type int*.

      If you do this instead:

      It's easy to misinterpret this as a pointer to a function that returns an plain int.

      For that reason, I find using attaching the * to the type for return values clearer.

      Make sense?

      I've updated lesson 6.7 to differentiate these two cases.

  • lt1

    Hi Alex,

    I have a question about the following program:

    int& Value(FixedArray25 &rArray, int nIndex)
        return rArray.anValue[nIndex];

    Can we consider a reference as a dereferenced pointer? If we can consider so, when we call the function above, the Value can be consider as a pointer to rArray.anValue[nIndex], but when the function is finished, the rArray.anValue[nIndex] will go out of scope, and the Value will pointing to a garbage. Is there something wrong?

    Thank you for your good tutorial!!!

    • Alex

      Yes, one way to think about references is to consider them as implicitly-dereferenced pointers. Another way is to consider them as aliases to the underlying data.

      I think your function should work fine. When the function terminates, the rArray reference goes out of scope, but the underlying data (the value you passed in for rArray) does not. Consequently, the reference returned by Value is still valid after the function terminates.

  • Reinstein

    HI Alex. Many thanks to you. You are crafting programmers out of many

  • MrFinn

    PS. The latter example in the text works for this same reason, the struct is declared in gobal scope and therefore still keeps on existing after the function call.

  • MrFinn

    I found this sentence (from MSVC++ documentation) to be very clarifying:

    "A reference holds the address of an object, but behaves syntactically like an object."

    Therefore, the object which is passed back to the caller must keep on existing (and it's address as well) when the function goes out of scope. This is why you can not pass reference to a local variable which ceases to exist. If you change the orginal sample code so that nValue is declared in global scope it will work because nValue object stays alive.

    int nValue; // declared in global scope.

    int& DoubleValue(int nX) {
    //int nValue = nX * 2;
    nValue = nX * 2;
    return nValue;

    BTW. Sunnys program does return the same error message here (Qt & MinGW) and the math is wrong:
    "warning: reference to local variable 'nValue' returned [enabled by default]"

  • Sunny Chouhan

    Hi Alex,
    As Mention in your article 'Return by reference' local variable cannot be return because they go out of scope when function returns.
    But I did not receive any compile error
    program is running fine
    I am using visual studio 2010 (vc++)

    using namespace std;

    int main()
    int &DoubleValue(int x);
    int number;
    number = DoubleValue(10);
    cout << "Number = " << number << endl;
    cin.ignore(255, '\n');
    return 0;
    int& DoubleValue(int nX)
    int nValue = nX * 2;
    return nValue; // return a reference to nValue here

    • vipul

      what is the diffrence betn int &DoubleValue(int x); and int& DoubleValue(int nX) ?i am stucked in int& and int &!!!!please understand this

    • Alex

      It's possible that since you're printing the value of number immediately, the value of nValue in the function hasn't actually been destroyed/overwritten yet.

      Trying to access a reference to a variable that has been destroyed will lead to unpredictable results, and should be avoided.

  • ellankavi

    In the following code, is the dynamic array deleted properly?

    Thanks :)

  • pankaj

    I try to return the value of the local variable by using return by reference. It is possible to do that.
    I am getting the correct values.
    Compiler is only giving waring...warning C4172: returning address of local variable or temporary

    plese see the code below and kindly give your comments..

    • Alex

      Returning a reference to a local variable is something you shouldn't do, as you'd be returning a reference to a value that is being destroyed when the function ends.

  • How does a varible passed by reference, change the original variable's data while being modified at once? (I know this sounds confusing but please try to understand :)

    • Kurt

      A reference works like an alias for the original data. You're not changing the value of the reference itself, because references are in a sense immutable. You're changing the value of the data the reference aliases. It's like modifying the dereferenced value of a pointer.

  • five

    Hey Alex and also everyone on this site. This is an extremely great site, I've "favorite'd' hhaha many c++ sites around the web, but goodness, this is some good stuff here..Even though this section just whizzes right over my head, I havnt seen a site that explains c++ this well. Anyway, 7-7.4 thus far is smoking my there another angle to look at this section from, haha, seriously though.

    Five aka Mersinarii


  • Thaaaaank u Mr,Alex ..
    useful tutorial

  • Kerrick

    Can you use the static keyword with a local variable in order to return it by reference or address? Thanks for these tutorials by the way.

  • Tony

    Functions can be lvalues? Did you just use a function as an lvalue in the return by reference example?

  • Ben


    I tried to define a dynamic array in the main() function

    then initialize it in another function (called after the definition):

    It compiles fine, but when I run it, it tells me that "anTest was not initialized".

    So how can I define or initialize a dynamic array in a function then send it back to my main function? I can't really use the Return by address because I have more than one dynamic array to define in the same function.

    I need to do that because the size of my arrays will be read from a file (i.e "ReadInput()") but the arrays will be used throughout my program and therefore should belong to the main() function. Oh and except the size, all the information in those 2 arrays will also be read from the file, so I don't know how I could define them afterwards.

    • Great question. The problem here is that when you pass anTest to ReadInput(), the address that anTest is holding is COPIED into pn. This means that when you allocate a dynamic array into pn, you're essentially overwriting the copied address, and the value of anTest never gets changed.

      What you need to do is pass the pointer by reference, so that when you assign your dynamic array to pn, you'll actually be assigning the value to anTest, and not a copy of anTest.

      You can do that by changing your declaration of ReadInput to the following:

  • Ben


    Is there a way to pass something back to the main function without returning it.

    For example, I want to create a function that reads data from the user: arguments are number of data to be entered and type of those data (int, double, char...). So I thought I would create a dynamic array of the required size and type (by using "switch"). But how can I pass that array back to the main function? Actually the way I want to define my function there's no "return", it would have to be a "void".

    And we can't overload the returning type so this doesn't help me much.

    Maybe a better way to do it would be to pass the dynamic array as an argument with the appropriate type so I could use function overloading. It's kind of avoiding the issue without solving it though. Plus how can you find the length of a dynamic array? (something equivalent to "strlen" for example).



    • If you need to pass back an object from a function with a void return type, pass it as a reference parameter.

      There's no way to find the length of a dynamic array that I know of. This is always one of the things that's bugged me about C++ (doubly so because the C++ runtime has to know the length of the array in order to delete it).

      • Ben

        Sorry I'm not clear with your answer. Could you refer me to the appropriate chapter or show me an exemple?

        I understand "Return by Reference" but what is "Pass back as a Reference parameter"?

        • I'm referring to the concepts in the lesson on reference parameters.

          For example:

          Reference parameters give you the ability to change the value of the variable passed in, so you can use them to essentially return things from your function without using a return value. For example, the above function foo() returns 5 in nX.

      • dimonic

        Excuse the late reply - I found this from a google search.

        Isn't it more likely the c++ runtime that deletes arrays? So the compiler cannot tell how big an allocated array will be (becuase it can be allocated by a variable amount). So if you want an array you can tell the siz of, you should use an stl vector.


    I am glad to see a number of indian names here such as Abhishek and Prabhakar using Internet to their advantage.

    I have been quietly reading through your tutorials on c++ and I must admit it is one of the best!!


    DEAR ALEX, your extremely fast responce to my query, by adding section 7.4a on 26th feb itself --i am overjoyed that my query deserved attention. thanks. i will persue c++ more vigorously. please extend your best wishes for me to have patience PRABHAKAR

Leave a Comment

Put all code inside code tags: [code]your code here[/code]