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

  • imiltsiass

    owboy boots come in cow leather however, many are created from more exotic animal skins such as alligator, snake, hippo, ostrich, buffalo grass, elk and the stingray.
    When purchasing a great fitting pair of cowboy boots your first move you should be aware of is actually that cowboy boots really do not fit exactly the same way while other boots and shoes do.One must always always have your toes measured by way of the shoe salesman and never shop with regard to cowboy boots initial thing early in the day.Save cowboy shopping (and any sort of shoe shopping) before after supper, midday not to mention mid afternoon is a good, as your feet expand all over the course of the day.The reverse well spoken if you acquire boots after sunset after being for your feet all day come a suowboy boots come in cow leather however, many are created from more exotic animal skins such as alligator, snake, hippo, ostrich, buffalo grass, elk and the stingray.

    When purchasing a great fitting pair of cowboy boots your first move you should be aware of is actually that cowboy boots really do not fit exactly the same way while other boots and shoes do.One must always always have your toes measured by way of the shoe salesman and never shop with regard to cowboy boots initial thing early in the day.Save cowboy shopping (and any sort of shoe shopping) before after supper, midday not to mention mid afternoon is a good, as your feet expand all over the course of the day.The reverse well spoken if you acquire boots after sunset after being for your feet all day come a subsequent morning the particular boots might be far too large for a comfort! After you could have your ankle measurement into position, turn your awareness of your your feet.The digits of cowboy boots may not be all cut an identical way.Some boots are fashioned with boxy your feet, others with pointy toes nevertheless others with rounded ft.A great many of cowboy shoes or boots both for each gender are made using pointy digits so pick and choose carefully based on the shape of your foot.

    Your best option for some women is to purchase few of cowboy overshoes in sometimes a boy's or perhaps small mens size.This at the same time works the same when you've got wide paws.Generally speaking, women's cowboy boots are fashioned with some B wider and men are a D wider.For people that have wide feet look for boots which might be made with a "wide width" or just shop while in the department designed for boys boots or shoes and shoes or boots.

    Heel heights are definitely the next interest.Cowboy boots consists of several heels, within the smallest in the tallest.Ladies may wish to go with a short heeled start for regular wear as well as a high heeled cowboy boot for night fun.A pleasant boot is one allows the actual foot to help slide easily into it and remember that the seam the spot where the leg of your boot attaches on the shoe system of the boot should not be binding (or confining) at all.Your toes should wiggle and navigate somewhat in the boot and once you get up to walk the heel of this boot really should slide a little tiny bit in the heel.

  • expeditiongoose

    itely have gone with the bankruptcy experience can suggest some manufacturers.You get an knowledge into the correct way competent the particular lawyer might be.If you're sure an legal representative, he or simply she could refer yourself to some excellent bankruptcy lawyers.
    Bankruptcy may be a complex legalised process, for this reason, it is really important to have a bankruptcy lawyer who are able to put send legal strategies to either block out the financial debt by liquidating ones own assets along with distributing these people amongst your creditors, or establish a repayment system.Usually the main consultation with a bankritely have gone with the bankruptcy experience can suggest some manufacturers.You get an knowledge into the correct way competent the particular lawyer might be.If you're sure an legal representative, he or simply she could refer yourself to some excellent bankruptcy lawyers.

    Bankruptcy may be a complex legalised process, for this reason, it is really important to have a bankruptcy lawyer who are able to put send legal strategies to either block out the financial debt by liquidating ones own assets along with distributing these people amongst your creditors, or establish a repayment system.Usually the main consultation with a bankruptcy lawyer or attorney is 100 % free, so you need to put send your real particular predicament before him or her.Once you have got hired a good bankruptcy legal practitioner, provide your pet with a list of all that debts for you to carry.This is able to include credit cards, medical bills, loans, passenger cars, etc.You need to have ones bankruptcy lawyer explain to you all the facts of the fresh law.For people with any requests, do not even hesitate in order to ask.

    Getting a Good Bankruptcy hearing Lawyer

    A decent bankruptcy lawyer can provide expert suggestions about how to get your finances back ready.A fine lawyer will allow you with compensation plans in addition to debt management.Before you actually finalize take your pick you need to share a ease and comfort with a bankruptcy attorney.

    You will want lawyer who seem to understands the system and do a good job to be able to represent you actually.It may financially impact you extra but you receive what you finance.Your area bar association can probably help you opt whether some proposed charge is fair using the local regular.You are also able to browse over the internet to evaluate some services to receive an idea what amount of it would financially impact you to use a individual bankruptcy lawyer.

  • esluankereke

    [b]<a href="http://www.timberlandkutunihon.com/boat-shoes-outlet-c-9.htmtimberland boat shoes women
    timberland boots on sale

  • customer to explore your place of business.Be superior about your objective.
    You have to be clear about your objective because it dictates any actions.If your call to action is a phone call then be sure you answer along with a friendly and upbeat speech.If your call to action is to travel your place of business then be sure to open before its due.If you give a coupon then be sure you honor the idea.If you offer a one-hour 100 % free consultation then make certain it's one-hour and also free.Be sure you can satisfy the demand of your call to action, no subject what it can be.
    Let's say your target is slightly successful? What happens when your call to action does not result in a sale? Your marketing strategy should address this.Should you have a process available to follow-up withcustomer to explore your place of business.Be superior about your objective.

    You have to be clear about your objective because it dictates any actions.If your call to action is a phone call then be sure you answer along with a friendly and upbeat speech.If your call to action is to travel your place of business then be sure to open before its due.If you give a coupon then be sure you honor the idea.If you offer a one-hour 100 % free consultation then make certain it's one-hour and also free.Be sure you can satisfy the demand of your call to action, no subject what it can be.

    Let's say your target is slightly successful? What happens when your call to action does not result in a sale? Your marketing strategy should address this.Should you have a process available to follow-up with the candidate? Of study course, you really should have a process available to post disaster with the chance.

    Do you want to know a new secret? Your prospects is going to do exactly because you ask.My first articles inquired readers to register for my best weekly ezine.And that may be exactly the things prospects does.Prospects came to my internet commerce website and subscribed to the ezine but pretty much never bought my products.Ouch! Don't continue doing this mistake.Request the sale made first afterward offer the ezine and / or newsletter if a prospect won't buy.

    Therefore, if that you do not get a good prospect to acquire on to begin with contact then offer so that you can send these a catalogue or e-zine.You only want get contact knowledge.Maybe the prospect wants to acquire but has got another barrier such as no cash today.Remember a new prospect isn't a wierder! It might take periodic contact to turn a prospect right customer.

    Tactics tend to be more effective once used within the framework of an strategy.Your marketing strategy should have a very stated final results.You ought to call your current prospect to make sure you action.You must have the ability to meet your demand of the call to action.Your marketing strategy should have a very contingency to maintain contact along with a prospect assuming they don't buy.It's in addition good home business sense to maintain contact from a prospect has become a paying customer.It's cheaper to maintain a user then have a new a single.

    Failing to possess a marketing plan will give you eager for customers.

  • nrayeinmmi

    a year later each friend about mine revealed me a new article listing script that he or she had just simply purchased and additionally installed.Initially I was hesitant when i was convinced many outgoing connections are damaging.I soon realized that for people with loads associated with fresh material, the outgoing links really don't matter.
    So I began my visit a good post directory set of scripts.After doing 100s of google queries and engaging in hours about research I hasn't been sure the one to consider.I then thought i would just go together with the script he had purchased.I acquired the script around one one hundred and seventy-five dollars along with made that back in about some months.Six several months later I'm sure making almost $ 100 a moment from msn adsense from article listing alone.
    Do you know why are piece of writing directory scripts for ta year later each friend about mine revealed me a new article listing script that he or she had just simply purchased and additionally installed.Initially I was hesitant when i was convinced many outgoing connections are damaging.I soon realized that for people with loads associated with fresh material, the outgoing links really don't matter.

    So I began my visit a good post directory set of scripts.After doing 100s of google queries and engaging in hours about research I hasn't been sure the one to consider.I then thought i would just go together with the script he had purchased.I acquired the script around one one hundred and seventy-five dollars along with made that back in about some months.Six several months later I'm sure making almost $ 100 a moment from msn adsense from article listing alone.

    Do you know why are piece of writing directory scripts for that reason profitable? Once you discover much about internet website marketing at all then you know standard phrase, material is important.Article Web sites provide hundreds of it as well as being fresh content and articles.Content is the most recognized thing which will major yahoo and google look meant for.Once all the articles are purchased by search engines, they are offered to come up on queries.

    Articles were created on every single thinkable area of interest from Nike athletic shoes to develop a family home.This methods, if you possess an post on grooming a good cat as an illustration, the article through your directory may expand for the fact that search.When released comes up there is your msn ads right ahead of that human beings face.That you're no longer on a one keyword phrase site big.You have thousands about different keywords for people to find your blog.

    The true beauty is which you can maintain a story directory script very easily.The merely think I truly do is log towards the back mother board of our site every day and invest about 10 units approving or possibly denying cutting edge articles, i mean it.The html and devices is done by your script.

    We have found exactly what I did so to begin my report directory.

    1.Earliest I authorised my dominion.
    a pair of.I purchased the script and also company WE purchased it all from applied it to my host without cost.
    3.I enrolled to experience free articles and reviews everyday right from articlemarketer.com just for fresh content each and every day for other parts of my life.
    3.I seated back and watched our adsense credit account grow.

    Follow all of these steps and will also be making great money each and every day with a personal article database script.

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