Page 246 - DCAP404 _Object Oriented Programming
P. 246
Unit 11: Pointers and Dynamic Memory Management
Swapped Values Notes
a = 4, b = 7
In the above example, the function swap ( )
creates reference ‘x’ for the first incoming integers and reference ‘y’ for the second incoming
integer. Thus the original values are worked with but by using the names x and y. The function
call is the simple one i.e.;
swap (a,b);
but the function declaration and definition include the reference symbol &. The function
declaration and definition, both, start as
void swap(int &, int &)
Therefore, by passing the references the function works with the original values (i.e., the same
memory area in which original values are stored) but it uses alias names to refer to them. Thus,
the values are not duplicated.
11.4.1 Pointers to Functions
When the pointers are passed to the function, the addresses of actual arguments in the calling
function are copied into formal arguments of the called function. This means that using the
formal arguments (the addresses of original values) in the called function, we can make changes
in the actual arguments of the calling function.
Example: Program to swap values of two variables by passing pointers.
#include<iostream.h>
#include<conio.h> // for clrscr( )
int main( )
{ clrscr( );
void swap(int *x, int *y);
// prototype
int a = 7, b = 4;
cout<< “Original values \n”;
cout<< “Original values \n”;
cout<< “ a=” << a << “,b=” << b<< “\n”;
Swap(&a, &b); // function call
cout<< “swapped values \n”;
cout<< “a=” << a <<, “b=” << b << “\n”;
return 0;
}
//function definition
void swap(int *x, int * y)
{ int temp;
LOVELY PROFESSIONAL UNIVERSITY 239