If you like my posts please leave a comment.

Thursday, November 29, 2012

Calling a Function by Passing the Pointer:



Calling a Function by Passing the Pointer:

In this section we will learn about – How to pass pointer to a function definition?
            When a pointer is passed to the function, the address of actual argument in the calling function is copied into the formal argument of the called function (function definition). Therefore here also, the called function does not create its own copy of original values; rather it refers to the original values by the address it receives. To understand this more consider the following example: The following example illustrates the swapping of two values by passing addresses through pointers.  

//Swapping of two values by passing address through pointers

#include <iostream.h>

void swap(int *, int *);                         

//--------------------------------------------

void swap (int *a, int *b)

{

int temp;

temp=*a;

*a=*b;

*b=temp;

}

int main()

{

int x=5;

int y=2;

cout<<"\n Original values were: \n";

cout<<"x = "<<x;

cout<<"\ny = "<<y;

swap(&x,&y);

cout<<"\n\n After swapping: \n\n";

cout<<"x = "<<x;

cout<<"\ny = "<<y;

}

Output:
Original values were:
x = 5
y = 2

After swapping:
x = 2
y = 5

No comments:

Post a Comment