The following two programs demonstrate calls by reference using
pointers
and references respectively:
/*****************************
File: call_pointer.C
*****************************/
#include <iostream.h>
int main()
{
int x = 10, y = 20;
void foo(int* , int* ); // Declare foo() with integer pointer
arguments
cout << "Before calling foo" << endl;
cout << "x = " << x << " y = " << y << endl;
foo(&x, &y); // Call foo() and pass two pointers
cout << "After calling foo" << endl;
cout << "x = " << x << " y = " << y << endl;
exit(0);
}
void foo(int *ptr1, int *ptr2)
{
*ptr1 += 10; // Change x by dereferencing ptr1
*ptr2 += 20; // Change y by dereferencing ptr2
}
Output:
Before calling foo
x = 10 y = 20
After calling foo
x = 20 y = 40
/*****************************
File: call_reference.C
*****************************/
#include <iostream.h>
int main()
{
int x = 10, y = 20;
void foo(int& , int& ); // Declare foo() with integer reference
arguments
cout << "Before calling foo" << endl;
cout << "x = " << x << " y = " << y << endl;
foo(x, y); // Call foo() and pass two references
cout << "After calling foo" << endl;
cout << "x = " << x << " y = " << y << endl;
exit(0);
}
void foo(int &ref1, int &ref2)
{
ref1 += 10; // increment x using ref1
ref2 += 20; // increment y using ref2
}
Output:
Before calling foo
x = 10 y = 20
After calling foo
x = 20 y = 40