Functions and Pointers

From WikiEducator
Jump to: navigation, search

Functions and Pointers :

Pointers could be passed to functions as parameters just like we pass ordinary variables as parameters to the functions: Let’s understand how to pass pointers to a function by an example code:

 main( )
 {
  int x = 70 ;
  cout<< x;
  IncreaseByTen( &x ); // calling the function IncreaseByTen passing     // address of x
  cout<<  x;
 }   
 //function IncreaseByTen
 void IncreaseByTen(int *ptr )
 {
   *ptr += 10;
 }

Predict the output of the above code.
The output of the above code snippet would be 70 and 80. This is because we have called the function IncreaseByTen( ) by passing the address of the variable x as an actual parameter. This address is being copied into the formal parameter ptr of the function, which is a pointer variable. Since this variable holds the address of the x so any changes made at this address ( by statement : *ptr+=10 ) would made changes on the value stored at that address i.e. on the value of x.
Similarly we can have more than one pointer variables as formal parameters to a function separated by comma.