FunctionX - Practical Learning Logo

Passing Arguments

This example demonstrates different techniques of passing arguments: by value, by reference, and as pointers

Source File
#include <iostream.h>



void main()

{

	int Boys = 3, Girls = 5;

	void PassByValue(int males, int females);

	void Reference(int &m, int &f);

	void Pointers(int *u, int *v);

	

	cout << "At startup, within main()";

	cout << "\n\tBoys  = " << Boys;

	cout << "\n\tGirls = " << Girls;



	cout << "\nPassing arguments by value = Copy";

	PassByValue(Boys, Girls);

	cout << "\nAfter calling PassByValue(), within main()";

	cout << "\n\tBoys  = " << Boys;

	cout << "\n\tGirls = " << Girls;



	cout << "\nPassing arguments by reference";

	Reference(Boys, Girls);

	cout << "\nAfter calling Reference(), within main()";

	cout << "\n\tBoys  = " << Boys;

	cout << "\n\tGirls = " << Girls;



	cout << "\nPassing arguments pointers";

	Pointers(&Boys, &Girls);

	cout << "\nAfter calling Pointers(), within main()";

	cout << "\n\tBoys  = " << Boys;

	cout << "\n\tGirls = " << Girls;

	cout << "\n";

}



void PassByValue(int b, int g)

{

	b += 3, g += 4;



	cout << "\nWithin PassByValue(), now";

	cout << "\n\tBoys  = " << b;

	cout << "\n\tGirls = " << g;

}



void Reference(int &b, int &g)

{

	b = b + 8, g = g + 5;



	cout << "\nWithin Reference(), now";

	cout << "\n\tBoys  = " << b;

	cout << "\n\tGirls = " << g;

}



void Pointers(int *b, int *g)

{

	*b = 44, *g = 52;



	cout << "\nWithin Pointers(), now";

	cout << "\n\tBoys  = " << *b;

	cout << "\n\tGirls = " << *g;

}

This would produce:
 
At startup, within main()

        Boys  = 3

        Girls = 5

Passing arguments by value = Copy

Within PassByValue(), now

        Boys  = 6

        Girls = 9

After calling PassByValue(), within main()

        Boys  = 3

        Girls = 5

Passing arguments by reference

Within Reference(), now

        Boys  = 11

        Girls = 10

After calling Reference(), within main()

        Boys  = 11

        Girls = 10

Passing arguments pointers

Within Pointers(), now

        Boys  = 44

        Girls = 52

After calling Pointers(), within main()

        Boys  = 44

        Girls = 52
 

C++ Tutorial Copyright © 2001 FunctionX, Inc.