Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Why use ambersand in front of C++ variable

Posted on 2011-03-23
12
Medium Priority
?
450 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 45

Assisted Solution

by:AndyAinscow
AndyAinscow earned 668 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 668 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: 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.

 
LVL 45

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 45

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 664 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

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

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

Okay. So what exactly is the problem here? How often have we come across situations where we need to know if two strings are 'similar' but not necessarily the same? I have, plenty of times. Until recently, I thought any functionality like that wo…
Article by: Nadia
Suppose you use Uber application as a rider and you request a ride to go from one place to another. Your driver just arrived at the parking lot of your place. The only thing you know about the ride is the license plate number. How do you find your U…
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…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses

609 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