Functions with pass by reference

This is the same idea with a function half that receives a variable by reference. The code is slightly different: instead of just an & in the function we use a *. This explicitly says that an address is required. Notice that the calling statement says half(&num); , explicitly specifying the address.

The variable a in half is called a pointer.

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

When main calls half, it passes the address of num to half. Inside function half, a contains the address of num.

Notice that in line 15 we say *a=*a/2; We want to find half the value of a, not half of the address. This is called dereferencing the pointer.

NEXT: Arguments must match