Solved

Why use ambersand in front of C++ variable

Posted on 2011-03-23
12
444 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 73

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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to check if url exists using c++? 6 636
source code to scan multiple images 6 90
wordsFront challenge 8 88
How to measure sizes and angles in scanned images ? 3 63
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…
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…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …

770 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