Search

7.4a — 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 parameters 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 when the function returns, we need to consider the effect of this on each return type.

(Author’s note: This lesson has a funny lesson number because it was originally omitted from chapter 7)

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 (eg. 5), variables (eg. x), or expressions (eg. 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. Because the variables are evaluated before the function goes out of scope, and a copy of the value is returned to the caller, there are no problems when the 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.

Return by reference

Just like with pass by reference, values returned by reference must be variables (you can not return a reference to a literal or an expression). 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, returning by reference has one additional downside that pass by reference doesn’t -- you can not return local variables to the function by reference. Consider the following example:

See the problem here? The function is trying to return a reference to a value that is going to go out of scope when the function returns. This would mean the caller receives a reference to garbage. Fortunately, your compiler will give you an 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:

5

When we call Value(sMyArray, 10), Value() returns a reference to the element of the array inside sMyArray that has the index 10. main() then uses this reference to assign that element the value 5.

Although this is somewhat of a contrived example (because you could access sMyArray.anValue directly), once you learn about classes you will find a lot more uses for returning values by reference.

Return by address

Returning by address involves returning the address of a variable to the caller. Just like pass by address, return by address can only return the address of a variable, not a literal or an expression. Like return by reference, return by address is fast. However, as with return by reference, return by address can not return local variables:

As you can see here, nValue goes out of scope 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, which will cause lots of problems if used. This is one of the most common programming mistakes 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 address they are returning will be to a valid variable after the function returns.

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

Conclusion

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!

7.5 -- Inline functions
Index
7.4 -- Passing arguments by address

69 comments to 7.4a — Returning values by value, reference, and address

  • 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 brain....is there another angle to look at this section from, haha, seriously though.

    Five aka Mersinarii

    :)

  • Kurt

    I'm breaking my head over this example.

    // This struct holds an array of 25 integers
    struct FixedArray25
    {
        int anValue[25];
    };
    
    // Returns a reference to the nIndex element of rArray
    int& Value(FixedArray25 &rArray, int nIndex)
    {
        return rArray.anValue[nIndex];
    }
    
    int main()
    {
        FixedArray25 sMyArray;
    
        // Set the 10th element of sMyArray to the value 5
        Value(sMyArray, 10) = 5;
    
        cout << sMyArray.anValue[10] << endl;
        return 0;
    }
    

    I don't understand how it knows where int& Value is referenced too.
    Am I wrong in this assumption:
    int& Value = Value(sMyArray, 10) = 5 do I have to ignore the part between the () so: int& Value = Value = 5
    I am looking at this code for a hour now and cant really understand what its doing, perhaps I need a break and come back with a fresh pair of eyes..

    Also a more logical example might help,
    why going trough all that extra code if
    Value(sMyArray, 10) = 5;
    could just as well be written
    sMyArray.anValue[11] = 5;

    • Kurt

      Typo in my last message:
      sMyArray.anValue[11] = 5; the 11 should be 10 ;)

      But I think I got it:

      int& Value = rArray.anValue[nIndex]

      or

      int& Value = Value(sMyArray, 10) = rArray.anValue[nIndex] = 5

      Made this:

      #include "stdafx.h"
      #include <iostream>
      
      using namespace std;
      
      
      
      // This struct holds an array of 25 integers
      struct FixedArray25
      {
          int anValue[25];
      };
      
      // Returns a reference to the nIndex element of rArray
      int &Value(FixedArray25 &rArray, int nIndex)
      {
          return rArray.anValue[nIndex];
      }
      
      int main()
      {
          FixedArray25 sMyArray;
      	int x; 
      	int y;
      	cout << "What array would you like to edit? (0-24)" << endl ;
      	cin >> x  ;
      	cout << "What value would you like attached to this array? (number between 0-255)" << endl;
      	cin >> y  ;
      
          // Sets element x of sMyArray to the value y
          Value(sMyArray, x) = y;
      
      	cout << endl << endl ;
      	cout << "Myarray" << x << " contains: " << sMyArray.anValue[x] << endl ;
      
      	return 0;
      
      }
      
  • 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.

    • I am not sure what you are angling at. The static keyword doesn't have anything to do with whether a variable is returned by reference or address.

      • jirka

        I believe Kerrick means something like that:

        // return by reference
        int& foo1() {
            static int val = 99;
            return val;
        }
        
        // return by address
        int* foo2() {
            static int val = 99;
            return &val;
        }
        

        In my oppinion this should work fine since "val" is not an "auto"
        variable and exists until the program terminates. As far as I can imagine,
        this approach would be useful only as some sort of Singleton design pattern
        or simillar stuff - otherwise it is a VERY BAD programming style.

  • Tony

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

  • Ben

    Alex,

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

    int *anTest

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

    int *anTest
    ReadInput(anTest)
    
    void ReadInput(int *pn)
    {
       nbpts = 10;
       pn = new int[nbpts];
    }

    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:

      void ReadInput(int *&pn)
      
  • Ben

    Alex,

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

    Thanks,

    Ben

    • 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 compiler 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:

          void foo(int &nX)
          {
              nX = 5;
          }
          
          int main()
          {
              int nX = 4;
              foo(nX); // nX will now equal 5
          }
          

          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.

  • INDIAN

    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!!

  • PRABHAKAR

    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 Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">