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

  • wholesaleearrin

    really are Student Universe, Travel Forms and sizes and STA.You require to fill in the registration info and then you can make make use of the various facilities on these webpages.
    Travel Shapes and STA request you to buy a major international Student Credit Card whereby Student Market asks you enter the email address of the school or college.This email is used in verification of this identity like a student.
    Additionally you can attain low-priced student plane tickets from various travel internet websites like Orbitz.They offer special provides to the students so, who buy tickets from them site.Students might also avail the reccommended discounted deals.So you will have a lot one could use.
    International visiting rates with regard to students can be further reduced.Students get extra discount of the fact that usual visitors.Airlines readily conform to the changing dates with students together with charge a lesser cancellation fee should the plane ticket is terminated.A student holds the clear ticket for a longer time of time over a travelers.
    For you to do some research prior to when you buy that ticket.You have to have a lot brows through th really are Student Universe, Travel Forms and sizes and STA.You require to fill in the registration info and then you can make make use of the various facilities on these webpages.

    Travel Shapes and STA request you to buy a major international Student Credit Card whereby Student Market asks you enter the email address of the school or college.This email is used in verification of this identity like a student.

    Additionally you can attain low-priced student plane tickets from various travel internet websites like Orbitz.They offer special provides to the students so, who buy tickets from them site.Students might also avail the reccommended discounted deals.So you will have a lot one could use.

    International visiting rates with regard to students can be further reduced.Students get extra discount of the fact that usual visitors.Airlines readily conform to the changing dates with students together with charge a lesser cancellation fee should the plane ticket is terminated.A student holds the clear ticket for a longer time of time over a travelers.

    For you to do some research prior to when you buy that ticket.You have to have a lot brows through the airlines and even student internet websites which offer you student flights.You ought of do all this prior to when you buy typically the ticket numerous experts end away saving some huge cash.

    You ought to keep positive things mentally while purchasing the student violation.Student airfare is mostly a new method of airfare built exclusively with the students given that students are often short relating to funds.This has been to be used as a result of students who would like to go to foreign countries for deeper studies or simply at other sorts of distant position.This is as well for all those students who definitely are living far from your family engaging in some exploration work and like to go home during summer vacations.

    Student airfare was initially offered by leading airlines.All it's good to show was your name card and you could get typically the ticket in a cheaper level.This do may or probably are not less over a discounted airfare wanted to the average user.So in the form of student, you should check that student air travel rates and even compare it again with those provided to the average user.

    Students might also get awesome discount offers assuming they buy a tickets thru some online websites like STA or simply Student Galaxy.Travel Cuts and STA get a hold of offline services and you could make some call in their eyes and ensure you get your ticket.However need ones identification proof prior to when the tickets are issued.

    Some websites take the assistance of search engines and display the best airfares for sale.They might also show all the discounts made available from the aircraft.Domestic discounts may perhaps be even raised above the individual discounts.

    To achieve the best option, students needs to be flexible with their schedules.Tickets have to be booked well earlier and on those times there is less website traffic.This you can get out online.Just stop by any travel around site and you will then get lots of the required information and facts.

    You may go for any cheaper aircraft.As students you should acquire the least costly airline and not just look for any comforts.Always be ready to implement smaller airports as long as they are not past the boundary away from the college.All this tends to help all the students to cut its traveling value and save lot of cash.

  • Speciale Gelegenheid Jurken 2013

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

  • Accessori da sposa - Aisle Style Regno Unito

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

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="">