Navigation



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.

int DoubleValue(int nX)
{
    int nValue = nX * 2;
    return nValue; // A copy of nValue will be returned here
} // nValue goes out of scope here

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:

int& DoubleValue(int nX)
{
    int nValue = nX * 2;
    return nValue; // return a reference to nValue here
} // nValue goes out of scope here

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 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;
}

This prints:

5

When we call Value(sMyArray, 10), Value() returns a reference to the 10th element of the array inside sMyArray. 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:

int* DoubleValue(int nX)
{
    int nValue = nX * 2;
    return &nValue; // return nValue by address here
} // nValue goes out of scope here

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 newly allocated memory to the caller:

int* AllocateArray(int nSize)
{
    return new int[nSize];
}

int main()
{
    int *pnArray = AllocateArray(25);
    // do stuff with pnArray

    delete[] pnArray;
    return 0;
}

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

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

  • 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

  • [...] 7.4a — Returning values by value, reference, and address [...]

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

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

  • 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)
      
  • Tony

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

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

  • Thaaaaank u Mr,Alex ..
    useful tutorial

  • 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;
      
      }
      
  • 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

    :)

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

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

    
    result of below code is 
    
    Hello World!
    res = 7
    res1 = 12
    
    int add (int x, int y)
    {
    int result = x+y;
    return result;
    }
    
    // return by reference
    int& multiply(int x, int y)
    {
     int result = x*y;
     return result;
    }
    
    int main(int argc, char* argv[])
    {
    	printf("Hello World!\n");
    	int res = add(3,4);
    	std::cout<< "res = " << res << std::endl; 
    
    	int res1 = multiply(3,4);
    	std::cout << "res1 = " << res1 << std::endl;
    	return 0;
    }
    
    • Anna
      But you can not be sure of how long that value exists and how
      long you can use that variable. Actually when you are
      returning from that function, the scope of that variable does
      not exist, but in memory there exists such an address and a
      value since nobody changes it. but there is a chance that
      when a new memory allocation is done by our process, the OS
      takes this memory and gives it.that time the value at this
      particular address might have changed and we may not be
      getting what we are expecting. in very simple terms using
      such a variable is just unsafe like using a property that we
      already sold. when the new owner comes you have to give it
      to that person and stop using it. but you never know when.
      such usage is very unsafe with big programs having multiple
      threads
      
      • mccp13

        what does the int& mean in pankaj’s function int& multiply(int, int)..
        does it mean it returns the address of an integer or a reference to an integer..
        and how did the local variable res1 int his main function accept the return type if the function?

        Nice Tutorial btw.. i’m using this to learn c++ :)

  • haya

    suppose i have to write one function to give me the highest and lowest and average how i will write it without using void?
    by using refrence but how?

  • ellankavi

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

    #include<iostream>
    
    int* CreateArray(int nSize)
    {
    	int* const npPtr = new int[nSize];
    
    	//initialize the array
    	for (int iii=0;iii<nSize;iii++)
    		npPtr[iii]=iii;
    	return npPtr;
    }
    
    int main()
    {
    	int nSize=5;
    	int *apArray=CreateArray(nSize);
    	delete[] apArray;
    	system("pause");
    	return 0;
    }
    

    Thanks :)

    • abcd

      My guess is, since apArray was not created using

      new int[]

      but rather something like

      int* apArray = int* npPtr

      it is most likely that the compiler does not take it as an Array.
      Try this:

      delete apArray

      Then access to any element will result in garbage

      std::cout <<  apArray[0];

      Once again, this is my guess. Hopefully Alex or someone else can verify this.

      BTW, great tutorial Alex! Thanks a ton.

  • vamsi
    Alex,
    
    Can you start STL tutorials
    
  • Hey Alex,

    great tutorial! It’s so amazing simple to learn C with your help, I’ve never thought before.

    I’ve found a little error he links aren’t correct:

    « 7.14 — Ellipses (and why to avoid them)
      13.1 — Input and output (I/O) streams »
  • 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++)

    #include
    using namespace std;

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

  • nimingzhe2008

    I have the same question as Sunny Chouhan.

  • [...] recap, for those who may be hazy on what a reference is in C++: When a variable is returned by reference, a reference to the variable is passed back to [...]

  • 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]“

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

  • developer

    Hi Alex

    i have a doubt here regarding references.
    we know that reference is a const pointer so we can initalize refernce only once.
    ie,
    int value = 5;
    int &ref = value;
    After this i cant change the value for ref.

    But in the above example

    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;
    }

    you are returning a refernce that is a const pointer to rArray.anValue[nIndex]
    and then you again assigning the value 5 to it.

    can you please clarify this.

  • [...] Returning values by value, reference, and address - learncpp.com [...]

  • Accessori da sposa – Aisle Style Regno Unito

  • ?????????????? weddingdressesoutlet.co.uk ???????????????

  • Speciale Gelegenheid Jurken 2013

You must be logged in to post a comment.