Solved

Why use ambersand in front of C++ variable

Posted on 2011-03-23
12
445 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
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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
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: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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

In Easy String Encryption Using CryptoAPI in C++ (http://www.experts-exchange.com/viewArticle.jsp?aid=1193) I described how to encrypt text and recommended that the encrypted text be stored as a series of hexadecimal digits -- because cyphertext may…
Prime numbers are natural numbers greater than 1 that have only two divisors (the number itself and 1). By “divisible” we mean dividend % divisor = 0 (% indicates MODULAR. It gives the reminder of a division operation). We’ll follow multiple approac…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
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…

828 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