Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Returning  a  Reference

You  can  also  return  a  reference  from  a  function.  When  a  function  returns  a  reference, the  function  call  can  exist  in  any  context  where  a  reference  can  exist,  including  being on  the  receiving  side  of  an  assignment.


Consider  the  following  function:



                       int  &  max ( int  &  x, int  &  y)
                       {

                                  if ( x > y )
                                           return  x ;
                                  else
                                           return  y ;

                       }



A  function  call  such  as  max (a , b ) returns  reference  to  a  or  b  depending  on  their values.  This  means  that  this  function  call  can  appear  on  the  left-hand  side  of  an assignment  statement.


That  is,  the  statement  


max (a , b)  =  -1 ;


is  legal  and  assigns  -1  to  a  if  it  is  larger, otherwise  -1  to  b.