Pass by Reference

Passing a value by reference allows the actual value outside of the function to be acted upon, as opposed to a copy of the value.

 

In passing a value by reference, C++ differs from C in that it allows any type of reference to be used (as opposed to just a pointer reference in C).

 

Accordingly, C++ allows values to be passed in using their normal identifier, and are then accepted within the formal parameter list of the function using the ampersand & (address of) reference operator:

 

#include <iostream>
using namespace std;

void myFunc(int & x, int & y) {

	x=x+y;
	y=x-y;
	x=x-y;

	cout << "x and y in myFunc: " << x << ", " << y << endl ;

}

int main () {

	int a = 17, b = 42 ;

	cout << "a and b in main before swap: " << a << ", " << b << endl ;

	myFunc(a, b) ;

	cout << "a and b in main: " << a << ", " << b << endl ;

	return 0;
}

Compile & Run:

a and b in main before swap: 17, 42
x and y in myFunc: 42, 17
a and b in main: 42, 17

 

Notice the swap of the values within the function has also affected the values in main()

Leave a Reply