Solved

Why use ambersand in front of C++ variable

Posted on 2011-03-23
12
442 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
  • 4
  • 3
  • 3
  • +2
12 Comments
 
LVL 44

Assisted Solution

by:AndyAinscow
AndyAinscow earned 167 total points
Comment Utility
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 73

Expert Comment

by:sdstuber
Comment Utility
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
Comment Utility
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
 
LVL 44

Expert Comment

by:AndyAinscow
Comment Utility
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
Comment Utility
oh wow - been typing slowly it seems heh.
0
 
LVL 44

Expert Comment

by:AndyAinscow
Comment Utility
Or just typeing more.  ;-)
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 53

Expert Comment

by:Infinity08
Comment Utility
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
Comment Utility
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
Comment Utility
Hmm, there was only one post when I started typing!
0
 
LVL 32

Expert Comment

by:phoffric
Comment Utility
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
Comment Utility
Surely you would always pass by reference then? When would you not?
Cheers for anwsers.
0
 
LVL 53

Expert Comment

by:Infinity08
Comment Utility
>> 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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Article by: Nadia
Linear search (searching each index in an array one by one) works almost everywhere but it is not optimal in many cases. Let's assume, we have a book which has 42949672960 pages. We also have a table of contents. Now we want to read the content on p…
The greatest common divisor (gcd) of two positive integers is their largest common divisor. Let's consider two numbers 12 and 20. The divisors of 12 are 1, 2, 3, 4, 6, 12 The divisors of 20 are 1, 2, 4, 5, 10 20 The highest number among the c…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

762 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

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now