Pass by Reference- Anyone with simple explanation

Why is this so confusing? Why putting the '&' symbol pass out the right value but without it, the function is useless.
1
2
3
4
5
6
7
8
9
10

void doubleNumber(int &num) { num = num* 2;}

int main()
{
  int num = 35;
  doubleNumber(num);
  cout<<num;
  return 0;
}

If someone can give me flow of the code, that may be helpful also!
Last edited on
There are two ways to pass an argument. By value and by reference.

Without the &, you're passing by value, which means the function is operating on a copy of the variable. Any changes made to the argument are made to the copy. The original variable is unaffected. The copy of the variable goes out of scope when the function exits.

With the &, you're passing by reference. This means the argument name is an alias for the variable in the caller. Any changes made to a reference argument are reflected in the caller's variable.
Just to show you the flow of the num value:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using std::cin;
using std::cout;


void doubleNumber(int &num)
{
    cout << "Function doubleNumber is called.\n";
    cout << "num = " << num << " prior executing num = num * 2\n";
    num = num * 2; 
    cout << "num = " << num << " after executing num = num * 2\n";
}

int main()
{
    int num = 35;
    cout << "num = " << num << " prior calling the function\n";
    doubleNumber(num);
    cout << "num = " << num << " final value\n";
    return 0;
}


Output:

num = 35 prior calling the function
Function doubleNumber is called.
num = 35 prior executing num = num * 2
num = 70 after executing num = num * 2
num = 70 final value
pass by value is using the number (having a photo of a person)
pass by reference is using the variable (having the actual person)
When you pass by reference you are giving the function access to the variable.
When you pass by value you are giving the function a copy of the variable.

Programmers pass by reference because it is more efficient than passing by value. For built-in data types (int, float, double etc...), the performance cost is relatively low. But for user-defined data types, passing by value can result in a performance hit because each object has to be copied. A solution to this is to pass by reference and if you do not want your objects to be changed, pass by constant reference.
When should you pass by reference and not by value? That's my problem with it. I just learned references yesterday.
Last edited on
It depends on the program you are making for it to matter. if the program is very small and will never deal with large amounts of data (volume and qty) then it is not huge deal either way.

As a rule I pass by reference unless it is not possible / or does not make sense to do so.

Passing by reference is cleaner to do generally because

1. Passing by reference keeps your program smaller in terms of its memory footprint.
2. Passing by reference it not as operationally expensive as passing by value.
When you pass by value, the compiler has to make an entire copy of the data, that is; declare a variable, allocate space, copy the data to the memory space, then free the space when done. And all of those things have checks and balance subprocesses to make sure nothing goes wrong or to tell you when something does go wrong (throw an error).

Step your program through its debugger when looking at how your compiler handles each type of variable to see how many more steps it takes to deal with passing by value variable/object vs passing by reference.

UK Marine said it best I think. Re-read his post.
Last edited on
Thanx a lot guys. This has been very helpful. So, correct me if I am wrong in this program, If I dont use '&' then when I do
>doubleNumber(35)
>num gets the value 35
> new num= 35 *2 = 70;
> BUT when the function exits, new num is deleted and num=35 because original value didn't change and only copy was changed which was out of scope. Thats why passing by reference solves this problem
Last edited on
I just wrote a program that has a reference. Is this considered "well" written?

Let me know if I am derailing this thread.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <iomanip>
using namespace std;

//func prototype*******************************************************
void kineticEnergy(double, double, double &);
//*********************************************************************

int main()
{

	double  velocity,
		     mass,
		     kE = 0;
	
	cout << "What is the object's mass that you wish to calculate in kilograms?" << endl;
	cin >> mass;

	cout << "What is the object's velocity that you wish to calculate in meters per second?" 
		<< endl;

	cin >> velocity;

	kineticEnergy(mass, velocity, kE);

	cout << "The kinetic energy of your object is " << kE << "." << endl;

	return 0;
}

//func header**********************************************************
void kineticEnergy(double mass, double velocity, double &kE)
{
	double  velocitySqr;

	velocitySqr = pow(velocity, 2.0);

	kE = (1.0 / 2.0) * mass * velocitySqr;
}
//********************************************************************* 
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <iomanip>
// using namespace std;

//func prototype*******************************************************

// void kineticEnergy(double, double, double &);

// favour value semantics over reference semantics
// document the function declaration with meaningful parameter names
double kineticEnergy( double mass, double velocity ) ;

//*********************************************************************

int main()
{
	double velocity ;
	double mass ; // favour declaring each variable on a separate line

	std::cout << "What is the object's mass in kilograms?\n";
	std::cin >> mass;

	std::cout << "What is the object's velocity in meters per second?\n";
	std::cin >> velocity;

	const double ke = kineticEnergy( mass, velocity );

	std::cout << "The kinetic energy of your object is " << ke << " joules.\n";
}

//func header**********************************************************
double kineticEnergy(double mass, double velocity )
{
	const double  velocitySqr = velocity * velocity ;

	return 0.5 * mass * velocitySqr;
}
//********************************************************************* 
Topic archived. No new replies allowed.