Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
References  as  Function  Parameters


References  are  often  used  as  function  parameters.  References  as  function  parameters offer  three  advantages:


1) They  eliminate  the  overhead  associated  with  passing  large  data  structures  as  parameters  and  with  returning  large  data  structures  from  functions.


2)  They  eliminate  the  pointer  dereferencing  notation  used  in  functions  to  which  you  pass  references  as  arguments.


3)  Like  pointers,  they  can  allow  the  called  function  to  operate  on  and  possibly  modify  the  caller's  copy  of  the  data.


Consider  the  following  example,



                                void  func( int  &  x )
                                {

                                              x  =  x  +  20 ;

                                }

                           
                                int  main ( )
                                {

                                             int  m  =  10 ;
                                             func( m ) ;
                                              - - - - -
                                              - - - - -
                                              - - - - -
                                             return  0;
                                }



When  the  function  call  func( m )  is  executed,  the  following  initialization  occurs:


int  &  x  =  m ;


Thus  x  becomes  an  alias  of  m  after  executing  the  statement


func( m ) ;


The  value  of  m  becomes  30  after  the  function  is  executed.  Such  function  calls  are known  as  call  by  reference