Solved

Why use ambersand in front of C++ variable

Posted on 2011-03-23
12
448 Views
Last Modified: 2012-05-11
This is as close to a recommended zone as I could get so sorry if its wrong.

Question is, why use an ambersand (&) before a variable in C++ when passing to a function.

I know it gets the memory address of the variable and not the variable contents - but why would you want to do that?
0
Comment
Question by:Johny_Brav0
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
  • +2
12 Comments
 
LVL 44

Assisted Solution

by:AndyAinscow
AndyAinscow earned 167 total points
ID: 35200493
Simple, it isn't a copy so any modifications in the function are to the variable itself, not a copy.

void X(int i)
{
  i = 17;
}

void Y(int& i)
{
 i = 42;
}

main()
{
  int i = 1;  
//i == 1
  Y(i);
//i == 42
  X(i);
//i == 42
}
0
 
LVL 74

Expert Comment

by:sdstuber
ID: 35200525
if your variable is a large structure then a pointer is smaller too,  so you consume less memory
because there is less to push on the stack

0
 
LVL 53

Accepted Solution

by:
Infinity08 earned 167 total points
ID: 35200531
There are two main reasons for this (either or both might be the reason for the specific case you talk about) :

(a) a memory address is a relatively small amount of data compared to a big object. Passing just the memory address is often more efficient than passing a copy of an entire object.

(b) passing the address allows the function to modify the original object, rather than receiving a copy of the object.


In C++, there is another mechanism that has these two benefits : references. Passing by reference should be preferred over passing by pointer whenever possible. So :

        void fun_byref(int& value) {   // by reference
            value = 10;   // modifies the original value
        }
       
        int i = 5;
        fun_byref(i); // passing by reference
        // i now has the value 10

versus :

        void fun_byptr(int* value) {   // by pointer
            *value = 10; // modifies the original value
        }
       
        int i = 5;
        fun_byptr(&i); // passing by pointer
        // i now has the value 10

versus :

        void fun_byval(int value) {   // by value
            value = 10;  // modifies a copy of the original value - the original value remains unchanged
        }
       
        int i = 5;
        fun_byval(i); // passing by value
        // i still has the value 5
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 44

Expert Comment

by:AndyAinscow
ID: 35200537
void X(int i)
{
  i = 17;
}

void Y(int& i)
{
 i = 42;
}

void Z(int* i)
{
(*i) = 99;
}

main()
{
  int i = 1;  
//i == 1
  Y(i);
//i == 42
  X(i);
//i == 42
  Z(&i);
//i == 99
}
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35200538
oh wow - been typing slowly it seems heh.
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 35200547
Or just typeing more.  ;-)
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35200551
and btw :

>> This is as close to a recommended zone as I could get so sorry if its wrong.

There is the C++ programming zone for questions related to C++ : http://www.experts-exchange.com/Programming/Languages/CPP/
0
 
LVL 32

Assisted Solution

by:phoffric
phoffric earned 166 total points
ID: 35200558
Even if you are passing a variable that is not going to be modified, then if that variable represents a large object (e.g., a large structure or vector), then you don't want to take the time to make a copy of that object onto the stack. Instead you just pass a reference to that object.

In the case where you do not want to modify the object being passed, then use the const attribute to enforce the rule that the function will not modify the passed object reference.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 35200568
Hmm, there was only one post when I started typing!
0
 
LVL 32

Expert Comment

by:phoffric
ID: 35200591
Ok, I just searched the other posts for "const", so I guess I didn't infringe upon other comments.
0
 

Author Comment

by:Johny_Brav0
ID: 35201601
Surely you would always pass by reference then? When would you not?
Cheers for anwsers.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 35201671
>> Surely you would always pass by reference then? When would you not?

Whenever you can, passing by reference is recommended.

There are some cases, where passing by reference doesn't work (the same) though ... When a NULL pointer is a valid value eg., or when you need to pass a pointer-to-pointer, or when you need to be able to make it point elsewhere.


Note furthermore that for small objects, it's probably more efficient to pass by value.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This algorithm (in C#) will resize any image down to a given size while maintaining the original aspect ratio. The maximum width and max height are both optional but if neither are given, the original image is returned. This example is designed t…
One of Google's most recent algorithm changes affecting local searches is entitled "The Pigeon Update." This update has dramatically enhanced search inquires for the keyword "Yelp." Google searches with the word "Yelp" included will now yield Yelp a…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…

690 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question