Introduction to Programming and C++

Contents Previous Topic Next Topic

In C++, the default means of passing paramters to a function is to create a copy of the argument. Like the originals, the parameters within a function can be modified, however, these modifications only affect the the parameter within the function. When the function returns, the original argument is unchanged. For example, Program 1 demonstrates this.

Program 1. Passing by value.

#include <iostream>

using namespace std;

void f( int n ) {
	cout << "Inside f( int ), the value of the parameter is " << n << endl;

	n += 37;

	cout << "Inside f( int ), the modified parameter is now " << n << endl;

	return;
}

int main() {
	int m = 612;

	cout << "The integer m = " << m << endl;

	cout << "Calling f( m )..." << endl;
	f( m );

	cout << "The integer m = " << m << endl; 

	return 0;
}

The behviour of Program 1 is shown in Figure 1.

Figure 1. The flow of Program 1; passing a variable by value.

In C, the only way that the function could modify one of its "arguments" was to actually pass the address of the argument instead. This address was still passed by value, however, the address could then be dereferenced and the memory location to which it points could be modified. Program 2 demonstrates this.

Program 2. Passing a pointer.

#include <iostream>

using namespace std;

void f( int * ptr ) {   // ptr is  a pointer to an int
	cout << "Inside f( int* ), the value pointed to "
             << "by the parameter is " << *ptr << endl;

	*ptr += 37;

	cout << "Inside f( int* ), the modified value pointed to "
	     << "by parameter is now " << *ptr << endl;
}

int main() {
	int m = 612;

	cout << "The integer m = " << m << endl;

	cout << "Calling f( &m )..." << endl;
	f( &m );

	cout << "The integer m = " << m << endl; 

	return 0;
}

The flow of Program 2 is shown in Figure 2.

Figure 2. The flow of Program 2; passing the address of m to the function..

Under certain circumstances, this is still used in C++, though it is possible now to pass by reference, that is, pass the actual object to be accessed and modified by the function.


Questions

1. Try this with other types: double and char.

2. Write a function void abs( int * n ) which sets the integer pointed to by the argument to its absolute value.

3. Given the function in Question 2, call abs( 0 ). What will happen?

4. Comment on the wisdom of a function like

      int m = -5;
      abs( &m );
      cout << "The value of m = " << m << endl;

modifying m without a visible assignment.

5. Write a function which takes two pointers to ints and swaps the values stored at those locations if the first is greater than the second. (hint)


Contents Previous Topic Top Next Topic