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

  • aumilodebede

    ur envelope will provide them an idea of all the bride together with grooms preferences and design and style, and formality.The colors for the wedding are generally intertwined on the invitation.Even though your wedding will be formal as well as informal the invitations should produce a great first impression.If you happen to choosing theme for your wedding make it into the invitations.As an illustration a traditional white wedding would be traditional and elegant in white.In a theme bottoms wedding such as an old movie will have antique look to it and also special clips out of your move inside it.A Nevada wedding has more style with glitter or gold confetti in the envelope.
    Spelling and grammar are likewise very important areas your marriaur envelope will provide them an idea of all the bride together with grooms preferences and design and style, and formality.The colors for the wedding are generally intertwined on the invitation.Even though your wedding will be formal as well as informal the invitations should produce a great first impression.If you happen to choosing theme for your wedding make it into the invitations.As an illustration a traditional white wedding would be traditional and elegant in white.In a theme bottoms wedding such as an old movie will have antique look to it and also special clips out of your move inside it.A Nevada wedding has more style with glitter or gold confetti in the envelope.

    Spelling and grammar are likewise very important areas your marriage invitation.The names really need to be presented in proper get and spelled correctly.Some people choose to write ones own wording for those invitation while others go with prewritten styles.

    Whichever you choose always proofread more than once for any kind of errors.It is helpful to have a few of those people in the area read the item; occasionally they often catch an error you pass-up.Make of course the address; dates, and times are usually correct.You do not need want everyone showing up at 2pm when wedding had been at 12.You should also include a new map as well as additional instructions on another paper into your invitation, that include whether little children are allowed and themes or templates.Letting any guests know prior to may relieve frustration later on.

    A wedding is mostly a day the lovely couple will always treasure, therefore all the invitations should certainly reflect a touch of them.Whether you have some formal conventional wedding or even themed beach party your invitations might reflect this also.Try to remember to benefit from proper syntax, spelling and always make sure to review.A specialized poem, writing or possibly traditional handmade about built welcomes others to join the celebration.Any wonderful instructions or even maps have to be on one additional sheet involving paper enclosed along with the invitation.A married relationship is a new celebration and therefore the invitation really should reflect your desire for getting the guest to attend.

  • fakehandbags

    dent propaganda.The person rights provider Global Experience received your grant from the government from the Great Britain for that development belonging to the effective process of tracking within the diamonds arriving in the market from Angola.Then Worldwide Witness has got started any unprecedented steps against contraband which has already led to the innovative changes through industry.In Antwerp :the international main deal center of diamonds - the world Diamond Congress under pressure of the public has launched the development of the international certification and supervising system to operate the import/export about rough gemstones.This system should get a barrier to the market for the purpose of deliveries regarding contraband rough diamonds coming from zones from military clashes.De Beers, established in 1888, is the world's leading diamond small business with unrivalled expertise in the exploration, mining and advertising of expensive diamonds.De Beers and its joint embark partners get the job done in a lot more than 20 cities across several continents employing.Earlier, De Ales Group - the international famous monopoly the fact that had explained shaky well-being of many African economics and also well-being involving diamond online business in The european union, Asia and America for a long time - has got reacted that will attack of the public.For more than seventy years, Southern African Group De Beers that has controlled sheduled delivery, selling and also diamond's prices, had resolved to the radical reforming.The Chairman of the De Ales Group Nicky Oppenheimer has arrived to London to describe new reforms towards its 125 joint venture partners.De Beers hosted the members conference and world conference during London.Delegates representing the governments of generating nations, non-governmental organizations, and the actual trade as well as general hit were at the same time in work.Laws of the free market had come to change gentlemen's arrangments made.This is actually contracts renewed time in two yrs by process "money forward".Besides De Soft drinks Group also would like to undertake operates of "policeman" on the market - on the rights regarding former monopoly it is going to control tdent propaganda.The person rights provider Global Experience received your grant from the government from the Great Britain for that development belonging to the effective process of tracking within the diamonds arriving in the market from Angola.Then Worldwide Witness has got started any unprecedented steps against contraband which has already led to the innovative changes through industry.In Antwerp :the international main deal center of diamonds - the world Diamond Congress under pressure of the public has launched the development of the international certification and supervising system to operate the import/export about rough gemstones.This system should get a barrier to the market for the purpose of deliveries regarding contraband rough diamonds coming from zones from military clashes.De Beers, established in 1888, is the world's leading diamond small business with unrivalled expertise in the exploration, mining and advertising of expensive diamonds.De Beers and its joint embark partners get the job done in a lot more than 20 cities across several continents employing.Earlier, De Ales Group - the international famous monopoly the fact that had explained shaky well-being of many African economics and also well-being involving diamond online business in The european union, Asia and America for a long time - has got reacted that will attack of the public.For more than seventy years, Southern African Group De Beers that has controlled sheduled delivery, selling and also diamond's prices, had resolved to the radical reforming.The Chairman of the De Ales Group Nicky Oppenheimer has arrived to London to describe new reforms towards its 125 joint venture partners.De Beers hosted the members conference and world conference during London.Delegates representing the governments of generating nations, non-governmental organizations, and the actual trade as well as general hit were at the same time in work.Laws of the free market had come to change gentlemen's arrangments made.This is actually contracts renewed time in two yrs by process "money forward".Besides De Soft drinks Group also would like to undertake operates of "policeman" on the market - on the rights regarding former monopoly it is going to control the particular accompanying documentation about the diamonds came to Antwerp.For many African nations, which within 30th many years had become free of colonialism, diamond areas are the main thing, if not the only thing, a source of incomes.Not casually issues in Sierra Leone, Angola, Congo, Liberia had inflamed because of the control more than diamond mines.The analysis of Antwerp's transactions had helped to complete the visualize of sexual penetration "bloody diamonds" with market.The scale associated with contraband amazes imagination.For instance, the official information :Liberia makes in one year 100 :150 500 carats.However, in the Belgian market only for five yrs (1994-1998) found registered thirty-one million carats regarding diamonds involving Liberian origins (app.6 million carats every year! ).The official mining associated with diamonds within Sierra Leone on 1998 have made 8, 5 thousand carats, and within Antwerp in the same 12 months had subscribed 770 a multitude carats for Sierra Leone's gems.In Sierra Leone the official government fails to control mines of the southeast of the country - all of them maintain by means of insurgents coming from Revolutionary designed front which unfortunately "had turned out to be famous" regarding terrorize neighborhood residents having chopping out them some brush for hands.How is it possible to stop the contraband? Richard Hoobrooke, the united states Ambassador to the United Countries, having accused a peace-making depending in Sierra Leone (about 3 multitude of people) in an inefficiency, had demanded to determine what equipment is necessary for purple helmets towards beat away from diamond mines in Revolutionary contained front.However, the other way of struggle :the creating of reliable system regarding certification involving diamonds :results simply in comical things.What might we do with the jewelry made of 10-20 jewels certified by just professional gurus? For instance, the diamond necklace will require up that will 30 certs, so the actual necklace's price will elevate greatly.Besides in the world no a lot more than five experts can define totally precisely via the diamond the spot of a mining.Four of these experts work at De Ales.At existing days any license meant for trade with diamonds in Antwerp is given out by any Belgian Generally High Council (HRD), - this is some kind of the buying guild the fact that closely associated with De Soft drinks.Its representatives refuse contraband's precious stones - many said that these diamonds received acted within the Belgian market from a small number of private agents.So the reason why criticize De Beers? The cause is the diamonds pricing.In truth, De Ales instantly purchased up jewels of anonymous origin to not admit any collapse of the market.Thus, De Ales had "choked" because of "swallowing" for unknown basis diamonds when the world local community had started referring to ethical aspects of business.But the cause is the not just in honorable aspects.The gemstone market is a colossus upon clay limbs.So, it is enough an easy whiff of the wind to help you stagger him or her:only 3 % of demand reduction means debts in 1, 6 billion dollars.Nowadays numerous experts anticipate that outsiders would like of shifting trade structure of the market to own advantage is an acronym behind disorders to De Drinks.The Belgian Minister associated with Foreign Matters had arrested Canada for attempts to help disorganize the particular Belgian diamond industry several months ago.The matter is which will Ottawa is going to mine generally fields from its Northwest area which meet or exceed African solutions and "are not necessarily blood diamonds".De Beers had announced that it is going to lower any huge wedding resources (up to help 5 million dollars), and it had promised to achieve a comprehensive transparency for diamond small business.Nowadays the large-scale advertising campaign is planned to support interest during diamonds.Thus, it is done the impression that the elected strategy is providing transition belonging to the control across the market for rough gemstones to domination in the market of slice diamonds.However, many specialists are sure that De Ales is scheming.The planet's famous monopolies (De Ales Group deals with 60% of the world promote of abrasive diamonds) will not die out of the blue.The organization just wants to wash separate the suggestions that the business had involved with African blood stream.

  • imiltsiass

    ration is professional.
    Referral customers may backlink to the reseller site and not buy at the start but return carryout a purchase days later.Consider affiliate courses that remember your web sites was responsible for that customer.The perfect affiliate systems remember anyone for 50 days with the use of cookies to tag the customers computer as soon as he visits the product owner site.
    One of the best affiliate sration is professional.

    Referral customers may backlink to the reseller site and not buy at the start but return carryout a purchase days later.Consider affiliate courses that remember your web sites was responsible for that customer.The perfect affiliate systems remember anyone for 50 days with the use of cookies to tag the customers computer as soon as he visits the product owner site.

    One of the best affiliate software programs offer reliable support along the lines of ads, art logos, and marketing advice.Good programs have timely tweets on then click through income and profit, and, be affected by questions or maybe problems within at any hour.

    Becoming Paid
    One can find three common affiliate monthly payment plans.Utilizing pay per sale, the mercantile pays as soon as the affiliate sends litigant who buys from the merchants site.
    The payment may well be a set amount maybe a percentage of the sale.

    In a pay per click traffic set all the way up, the affiliate is paid using the number of individuals who go to the merchant's web site regardless in case your purchase seemed to be made.Needless to say, some systems offer far more generous commission than some.You should read the terms of service to check you have a clue everything runs.

  • fakehandbags

    mmer in a couple ways.Firstly that surgeries reduce the sum of food absorbed.The gut is shrunk by creating a small pouch appears where food stuff enters and consequently less food items is consumed by patients.Restrictive weightloss surgery moreover make individuals feel extensive longer because the lower outlet belonging to the pouch created smaller to ensure that food empties gradually.
    Lap band plastic cosmetic surgery and Straight banded gastroplasty are examples of restrictive operations.
    Gastric detour around surgery may be a combination both the restrictive additionally, the malabsorptive medical operation.This surgery is done by preparing a small abdominal pouch to restrict the sum of food consumption.Then your bypass of the dmmer in a couple ways.Firstly that surgeries reduce the sum of food absorbed.The gut is shrunk by creating a small pouch appears where food stuff enters and consequently less food items is consumed by patients.Restrictive weightloss surgery moreover make individuals feel extensive longer because the lower outlet belonging to the pouch created smaller to ensure that food empties gradually.

    Lap band plastic cosmetic surgery and Straight banded gastroplasty are examples of restrictive operations.

    Gastric detour around surgery may be a combination both the restrictive additionally, the malabsorptive medical operation.This surgery is done by preparing a small abdominal pouch to restrict the sum of food consumption.Then your bypass of the duodenum besides other parts from the intestine is constructed to be able to cause malabsorption.Roux-en-Y gastric circumvent and Distal Gastric Avoid are plus the the gastric circumvent cosmetic weight loss surgery.

    A few of the health dangers of slimming surgeries?

    Health conditions are almost the same for either restrictive in addition to gastric sidestep surgeries wedding ceremony risk regarding nutritional inadequacies for calcium mineral, Vitamin B12 and iron will be higherin gastric avoid surgery clients.Intestinal leaking may additionally occur.

    Gastric evade surgery men and women may skilled the "Dumping Problem." It's when nutrition moves at the same time fast through the small intestine additionally, the patient may well experience a feeling of sickness, cold sweat, dizzy or fainting spells, some weakness and now and again, even diarrhea.

    Patient can choose either the conventional open surgery or laparoscopic sugery the particular latter remaining that there will be smaller scars plus less down-time since that bariatric medical procedures patient could recover faster.

    Similarly to any form of surgeries, patients should ask its surgeons which often for of cosmetic surgery is most effective for these.Before a person is committed to undergo a slimming surgery, he require tried many other healthy means to lose excess weight.A cosmetic weightloss surgery should always be the very last option when other efforts still did not help the person to decrease weight.

  • [b]<a href="http://es.montblancfountainpens4u.orgbolĂ­grafos
    plumas mont blanc

  • fakehandbags

    s can include personal kind of a automobile - quite possibly one that's a standard model.Whether it's really a personalized emblem with the driver's favorite rock-band or a bed that speaks to your engine underneath the hood's performance doesn't situation, personalized feel does.
    * Exciting.For many car devotees, it's just plain pleasurable to fine-tune out an auto with emblems, decals plus much more.Even a really plain car can be made to search extraordinary as a consequence of custom insignias.
    * Inventive freedom.Many auto enthusiasts find their cars as being a blank canvas, just waiting to get brushed right up with a few personal manifestation.Emblems, decals plus much more help greatly enhance a car's appearance and will give the owner a great outlet meant for artistic expression.
    And while there are various reasons in order to tweak out a car with insignias ans can include personal kind of a automobile - quite possibly one that's a standard model.Whether it's really a personalized emblem with the driver's favorite rock-band or a bed that speaks to your engine underneath the hood's performance doesn't situation, personalized feel does.

    * Exciting.For many car devotees, it's just plain pleasurable to fine-tune out an auto with emblems, decals plus much more.Even a really plain car can be made to search extraordinary as a consequence of custom insignias.

    * Inventive freedom.Many auto enthusiasts find their cars as being a blank canvas, just waiting to get brushed right up with a few personal manifestation.Emblems, decals plus much more help greatly enhance a car's appearance and will give the owner a great outlet meant for artistic expression.

    And while there are various reasons in order to tweak out a car with insignias and stickers, there are only as lots of, if not more, choices of such items so that you can jazz up a car with.Many of the items available through made to order emblem designers include:

    * Investment model emblem replacements.These will be replacements for the original emblems that are included with the automobiles.Not pretty exciting to get someone planning to really key out your automobile, nonetheless they serve an objective of by ensuring a auto remains a fact to a original appearance.

    * Tailor made emblems.There are several makers of these emblems which will take your car owner's recommendations and simply turn them right into great replacements for that stock emblems that include the autos.

    * Developer emblems.These kind of don't reflect personal layouts, but they may be great even now.Coming in several shapes, styles and styles, these symbols are popular with those who seem to don't wish to have a specialized emblem generated, but want something higher than a ride's commodity appearance.

    * Graphics.Basically stickers used to jazz right up an auto's outside appearance, these work effectively with emblems to offer a trip a tailor made look.

    It doesn't matter the style, design and also materials an auto owner may want, there's apt to be a made to order emblem out there.And, in case there's not, there's your maker prepared to be charged with the task.Tailor made outer appearances for motors help arranged them a part, allow owners to talk about themselves and so are just bare fun to experiment with.Taking part while in the trend is often as simple and additionally sophisticated while replacing just one emblem which includes a designer as well as custom one or going for a whole latest look on the lateral side of a car or truck.

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