Search

7.4 — Passing arguments by address

// The first half of this lesson is now in https://test.learncpp.com/cpp-tutorial/7-11-pass-by-pointer-and-return-by-pointer/

Addresses are actually passed by value

When you pass a pointer to a function, the pointer’s value (the address it points to) is copied from the argument to the function’s parameter. In other words, it’s passed by value! If you change the function parameter’s value, you are only changing a copy. Consequently, the original pointer argument will not be changed.

Here’s a sample program that illustrates this.

tempPtr receives a copy of the address that ptr is holding. Even though we change tempPtr to point at something else (nullptr), this does not change the value that ptr points to. Consequently, this program prints:

55

Note that even though the address itself is passed by value, you can still dereference that address to change the argument’s value. This is a common point of confusion, so let’s clarify:

  • When passing an argument by address, the function parameter variable receives a copy of the address from the argument. At this point, the function parameter and the argument both point to the same value.
  • If the function parameter is then dereferenced to change the value being pointed to, that will impact the value the argument is pointing to, since both the function parameter and argument are pointing to the same value!
  • If the function parameter is assigned a different address, that will not impact the argument, since the function parameter is a copy, and changing the copy won’t impact the original. After changing the function parameter’s address, the function parameter and argument will point to different values, so dereferencing the parameter and changing the value will no longer affect the value pointed to by the argument.

The following program illustrates the point:

This prints:

56

Passing addresses by reference

The next logical question is, “What if we want to change the address an argument points to from within the function?”. Turns out, this is surprisingly easy. You can simply pass the address by reference. The syntax for doing a reference to a pointer is a little strange (and easy to get backwards). However, if you do get it backwards, the compiler will give you an error.

The following program illustrates using a reference to a pointer:

When we run the program again with this version of the function, we get:

5 ptr is null

Which shows that calling setToNull() did indeed change the value of ptr from &five to nullptr!

There is only pass by value

Now that you understand the basic differences between passing by reference, address, and value, let’s get reductionist for a moment. :)

In the lesson on references, we briefly mentioned that references are typically implemented by the compiler as pointers. This means that behind the scenes, pass by reference is essentially just a pass by address (with access to the reference doing an implicit dereference).

And just above, we showed that pass by address is actually just passing an address by value!

Therefore, we can conclude that C++ really passes everything by value! The properties of pass by address (and reference) come solely from the fact that we can dereference the passed address to change the argument, which we can not do with a normal value parameter!

Pass by address makes modifiable parameters explicit

Consider the following example:

It’s not obvious from the call to foo2() that the function can modify variable i, is it?

For this reason, some guides recommend passing all modifiable arguments by address, so that it’s more obvious from an existing function call that an argument could be modified.

However, this comes with its own set of downsides: the caller might think they can pass in nullptr when they aren’t supposed to, and you now have to rigorously check for null pointers.

We lean towards the recommendation of passing non-optional modifiable parameters by reference. Even better, avoid modifiable parameters altogether.

Pros and cons of pass by address

Advantages of passing by address:

  • Pass by address allows a function to change the value of the argument, which is sometimes useful. Otherwise, const can be used to guarantee the function won’t change the argument. (However, if you want to do this with a non-pointer, you should use pass by reference instead).
  • Because a copy of the argument is not made, it is fast, even when used with large structs or classes.
  • We can return multiple values from a function via out parameters.

Disadvantages of passing by address:

  • Because literals (excepting C-style string literals) and expressions do not have addresses, pointer arguments must be normal variables.
  • All values must be checked to see whether they are null. Trying to dereference a null value will result in a crash. It is easy to forget to do this.
  • Because dereferencing a pointer is slower than accessing a value directly, accessing arguments passed by address is slower than accessing arguments passed by value.

When to use pass by address:

  • When passing built-in arrays (if you’re okay with the fact that they’ll decay into a pointer).
  • When passing a pointer and nullptr is a valid argument logically.

When not to use pass by address:

  • When passing a pointer and nullptr is not a valid argument logically (use pass by reference).
  • When passing structs or classes (use pass by reference).
  • When passing fundamental types (use pass by value).

As you can see, pass by address and pass by reference have almost identical advantages and disadvantages. Because pass by reference is generally safer than pass by address, pass by reference should be preferred in most cases.

Rule

Prefer pass by reference to pass by address whenever applicable.

%Missing lookup for lesson id 111%

68 comments to 7.4 — Passing arguments by address

  • perfectperfect

    p replaced by simply roller shoes.Those ended up big in your 70? 's and 50? s while roller discos and rearfoot warmers were widespread.Roller mower blades then did start to become favorite.These were being recreational inline skates which may have retained much the same style ever since.Now, aggressive skates are popular for people who want to perform tricks.What contains changed dramatically will be aggressive kind op replaced by simply roller shoes.Those ended up big in your 70? 's and 50? s while roller discos and rearfoot warmers were widespread.Roller mower blades then did start to become favorite.These were being recreational inline skates which may have retained much the same style ever since.Now, aggressive skates are popular for people who want to perform tricks.What contains changed dramatically will be aggressive kind of skating plus the ever ambitious tricks that the professional skaters accomplish.

    The needs of skate boarding equipment are more widely available than you ever have.Prices get dropped to the situation that forums, helmets, pillow-top, aggressive skates and various other accessories are from the budget in UK kids.It is not only just the skate boarding equipment that may be on the shopping list but also the garments and popular music.No self-respecting boarder or maybe skater can be without your cargo trousers and beanies along with Linkin Meadow and Avril Lavigne instantly be on their mp3 player.While much of the skate boarding in addition to aggressive skateboarding scene in england was imported from the States, our teens are generally proud to find out that many people started all the baggy apparel scene and it traveled Stateside.

  • fakehandbags

    taining to Navy Not to mention Marine Corps honours:"Where can one get the info for exactly how and were to put patches in for the self, my unit doesn't have funding to obtain my areas sewed for, so I must do them myself if I want to get squared aside.The Standard Regs Section 4, Section two will explain wherever you score badge etcetera.Needs to become placed upon each unvarying.As much as obtaining patches, navigate to the exchange online shop."
    "You'll have to setup a username & password should you haven't now.You may order all uniform products and nicotine patches on below.This is the main military return system, so everything continues to be tax absolutely free and you will find free shipping/returns.Items usually take under 1 week to arrive, as long because they have these products in share."
    "Your NOSC ought to provide this particular service.It really should not be your job to have to cover this from your own bank account.Tailoring as well as sewing on patches ought to be included, just not ribbons, warfare devices and so on.Both units I've been attached to did it.You're proper, but unfortunately you will find centers this don't do that.Mine, NOSC Minneapolis, is one of them.If something, keep the actual receipts for tax period.Well these people said they've no capital? Even when it's the itaining to Navy Not to mention Marine Corps honours:"Where can one get the info for exactly how and were to put patches in for the self, my unit doesn't have funding to obtain my areas sewed for, so I must do them myself if I want to get squared aside.The Standard Regs Section 4, Section two will explain wherever you score badge etcetera.Needs to become placed upon each unvarying.As much as obtaining patches, navigate to the exchange online shop."

    "You'll have to setup a username & password should you haven't now.You may order all uniform products and nicotine patches on below.This is the main military return system, so everything continues to be tax absolutely free and you will find free shipping/returns.Items usually take under 1 week to arrive, as long because they have these products in share."

    "Your NOSC ought to provide this particular service.It really should not be your job to have to cover this from your own bank account.Tailoring as well as sewing on patches ought to be included, just not ribbons, warfare devices and so on.Both units I've been attached to did it.You're proper, but unfortunately you will find centers this don't do that.Mine, NOSC Minneapolis, is one of them.If something, keep the actual receipts for tax period.Well these people said they've no capital? Even when it's the innovative fiscal time.Well my spouse knows how you can sew the actual patches for the shirts and understand how to hem any pants."

    "So all I must take towards the cleaners are the jackets.Normally if it's the 1st outfitting (either a brand new reservist or even NAVET) your NOSC will have all this sewing done for yourself.After the first outfitting however it is ordinarily the member's responsibility to achieve the patches use.That is actually how this Center will it at the bare minimum and I assume that would have to be model wide."

    "I am mounted on a ship and this drilling is actually spent on the deck of.As near to being dynamic duty like a reservist could be.As soon as i get this quails done I will be on any watch costs.So, therefore my NOSC is on the navy base by having an NEX right there.Depending upon where your NOSC is definitely, getting the actual patches done right, and your jumpers pressed right can be a problem for the purpose of folks not really familiar.They are normally pushed inside out, make sure where you go to, they understand what they're doing.There is really a civilian woman that flows a part-time tailoring business out of her house for our NOSC."

    "I had my cammies there to obtain everything sewn on as well as pinned all the nametapes & crows the place they needed to go along with explaining a uniform Regs.She still managed to screw up my include, even after telling me personally she obtained a copy from the uniform Regs to go by."

    "The Navy and Marine Corps Awards Manual, secnavinst 1650.1H, describes all Navy & Marine Corps awards, criteria, as well as eligibility.Go in order to ndaws and you will see a link to the manual on the right.I hope this doesn't sound way too obvious but the best place to start would be at this NOSC inside your service track record.Couldn't let you know exactly whereby but I know it should be in generally there."

    "There's absolutely nothing wrong together with your answer, however it assumes which his record is precise.I learned a long time ago not to create that prediction.By him or her researching it directly with the manual the guy:Learns where to consider the response to any long run questions on this subject, and Knows where you can direct your partner's Sailors to once they have a good question on this subject."

    "But this sounded for example he wanted to look about personally watch if he had been given the award and so i figured that would be the best destination to look.I guess he would probably need to discover both if he has it with his record and if not, what the actual qualifications are for that award.Thanks for that reminder.".

  • imiltsiass

    rogress over not a sufficient amount of.
    The earliest outfit that will pack could be the ski "stuff" if you have had them - boots, skis, and poles - given that not, typically the resorts hire them.Clothing calls for several coatings of clothing to last warm relating to the slopes, and to eliminate secure to loosen up.Thermal training pants, long-sleeved tee shirts or turtle-neck t shirts, thin socks who are moisture-wicking often is the first core closest for the skin.
    Typically the heavier level involves cardigans, sweatshirts, water-repellant skirts, thicker socks along the lines of "smart wool" who are moisture wicking.The outer-essentials to get first removals when heating might be a ski parka, chapeau, gloves, muffler or perhaps neck warmer being the day happens.Also important could be sunglasses or simply goggles meant for sun and additiorogress over not a sufficient amount of.

    The earliest outfit that will pack could be the ski "stuff" if you have had them - boots, skis, and poles - given that not, typically the resorts hire them.Clothing calls for several coatings of clothing to last warm relating to the slopes, and to eliminate secure to loosen up.Thermal training pants, long-sleeved tee shirts or turtle-neck t shirts, thin socks who are moisture-wicking often is the first core closest for the skin.

    Typically the heavier level involves cardigans, sweatshirts, water-repellant skirts, thicker socks along the lines of "smart wool" who are moisture wicking.The outer-essentials to get first removals when heating might be a ski parka, chapeau, gloves, muffler or perhaps neck warmer being the day happens.Also important could be sunglasses or simply goggles meant for sun and additionally snow glare.Concerning ski accommodations, temperatures determines a lot in the day, so possibly even sunscreen could be important for your glare with the sun and additionally snow also.

    Any time you plan on going sight-seeing or make purchases, simply transforming into nice and clean dry leg protection and snug boots could be enough, possibly going for the lodge regarding something to help you drink right after coming heli-copter flight slopes just might discover this fashion acceptable.The mainly time you'll want to worry regarding something fancier is through the evening hrs.If metropolis is minor and restful, the shorts and shirt could be enough for those evening.AND YET, if selecting a ski township is alot more formal, with the help of fancier public houses and discos, then fancier night time clothing could be needed.From formal, khakis maybe a nice two of pants or simply jeans, enticing shirts or perhaps sweaters, and then a coat.

    Any time you plan at booking weekly or a great deal more, pack any clothing plus personal pieces, then name the snowboarding resort and make them aware of you are shipping a stuff in their mind, and understand it held on the desk.For everybody who is flying or enjoy a small car with modest room - particularly if several persons are traveling mutually, this is really an option to suit your needs.Shipping are generally overnight, only two day, or some day in accordance with how way it has to travel.In accordance with how a great deal the proverbial box weighs, you are likely to usually pay underneath fifty pounds to ship a package while in the continental Country....which is not nearly as expensive you will pay any airline for extra travel luggage!

  • fakehandbags

    pouse and children products plus genuine food stuff containers.And also the these are a soup are able to safe, fence outlet, saltshaker, greens dressing jar, book, wax light, flowerpot diversion dependable, beer and additionally soda harmless, etc.Some diversion safes are also available in different solution names and various brands.They are really constructed that should be indistinguishable from the genuine product and are generally weighted so that you can pouse and children products plus genuine food stuff containers.And also the these are a soup are able to safe, fence outlet, saltshaker, greens dressing jar, book, wax light, flowerpot diversion dependable, beer and additionally soda harmless, etc.Some diversion safes are also available in different solution names and various brands.They are really constructed that should be indistinguishable from the genuine product and are generally weighted so that you can feel entire.They appearance and feeling like the real products, because of the bar codes.

    A lot of these hidden safes, once spread about your private home, make it again much harder to keep your belongings or dollars from simply being found by burglars and perhaps friends along with relatives and also require sticky hands and wrists.

    Primary benefits of these safes is usually cost.Use of hidden safes inside recommended trying to hide spots is undoubtedly an inexpensive alternative to popular the extra highly priced safes purchase for a whole bunch more finances.Prices generally utilize the $8.97 to $39.00, that happens to be way underneath most typical fireproof safes.Determined burglars could easily remove incredibly heavy safes, even models bolted up to the terrain.

    Diversion Safes is a unique home-security product.

    Help yourself without having it the robber; hide any valuables plus treasured stuff in bare sight!

  • erjavinchanc

    down benches.
    When buying home household furniture for use within a massive family's mudroom, you should look to get functionality.During the wintertime months probably the most used part of home furniture inside our home include the coat cabinets.There are usually two coating racks in the mudroom plus two topcoat racks on the main door way on the house.The kids coat wine racks are shorter compared to adult coat rackfor usefulness purposes.They've had any foot section taken out of them in making them shorter and a lot more accessible for the children.The coating racks contain the coats, sweaters, gloves plus winter less difficult.In the particular spring precious time coat shelving hold raincoats and umbrellas
    Another down benches.

    When buying home household furniture for use within a massive family's mudroom, you should look to get functionality.During the wintertime months probably the most used part of home furniture inside our home include the coat cabinets.There are usually two coating racks in the mudroom plus two topcoat racks on the main door way on the house.The kids coat wine racks are shorter compared to adult coat rackfor usefulness purposes.They've had any foot section taken out of them in making them shorter and a lot more accessible for the children.The coating racks contain the coats, sweaters, gloves plus winter less difficult.In the particular spring precious time coat shelving hold raincoats and umbrellas

    Another piece of useful pieces of furniture in your mudroom, in addition to a coat holder, is an important bench where close family can sit on when extracting their boots.This piece of home home furniture has drawers where children save their boots and overshoes.Each bathroom drawer is labeled having a child's name to protect yourself from any misunderstanding.

    A great sturdy doormat is likewise important to be able to wipe away from muddy and also wet boots.Purchase any recessed yoga exercise mat, as they are easily flushed and efficiently trap soil and moisture content.They are usually recommended because they're safe; not really a tripping risk.Another neat part of home furniture for yourself mudroom could possibly be the versatile armoire, filled with shelves and also hooks.Backpacks, bags and also purses could be stored inside here.

    When buying home furniture to your mudroom, buy a wall reflect, some added hooks in addition to a trash receptacle.Remember the fact that mudroom maintains mostly periodic items, once winter has ended keep clothes and shoes or boots away in storage.Constantly revisit the area and remove things that do never belong as a consequence keeping that clutter to the minimum.

    Having a limited budget including a small moment investment, a mudroom is often turned to a well sorted out space using a few furnishings pieces.A well organized mudroom can save you the frustration of interested in shoes plus coats in the am rush.

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