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 = 5Passing arguments by value = CopyWithin PassByValue(), now        Boys  = 6        Girls = 9After calling PassByValue(), within main()        Boys  = 3        Girls = 5Passing arguments by referenceWithin Reference(), now        Boys  = 11        Girls = 10After calling Reference(), within main()        Boys  = 11        Girls = 10Passing arguments pointersWithin Pointers(), now        Boys  = 44        Girls = 52After calling Pointers(), within main()        Boys  = 44        Girls = 52
 

C++ Tutorial Copyright 2001 FunctionX, Inc.