Functions with pass by reference

Instead of passing the values of variables to functions, we can pass the variable itself (its address) to a function. This is called "pass by reference".

In this example we use a function to give a variable a new value that is half its original value. Obviously, we could just say num=num/2; but this function illustrates pass by reference without getting too complicated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Pass by reference
#include<iostream>
using namespace std;
void getHalf(double&);
int main()
{
	double num;
	cout << "Enter a number:";
	cin >> num;
	getHalf(num);
	cout << "num is now " << num << endl;
	system("pause");
	return 0;
} //main
void getHalf(double &a) {
	a = a / 2;
}
CODE
Enter a number:12.5
Num is now 6.25
Press any key to continue . . .

The & next to the parameter in the function header tells the compiler to pass the address of the variable instead of its value.

half

When main calls half, it passes the address of num to half. Inside function half, this location in memory is referred to as a, but it is the same location as num that was declared in main. When half assigns a new value to a that is half its current value, it is actually changing the value of num in main.

NEXT: Finding half the value explicitly