


















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



















Lecture 30
In Today’s Lecture
Between References
and Pointers
int & i ; ‘i’ is a reference to an integer int * i ; ‘i’ is a pointer to an integer
Example 1 main ( ) { int i ; int & j = i ; i = 123 ; Output cout << i << endl ; 123 cout << j << endl ; 123 i++ ; cout << i << endl ; 124 cout << j ; 124 } Docsity.com
Example 2
void swap ( int x , int y )
{
int temp = x ; x = y ; y = temp ;
}
Example 2 main ( ) { int x , y ; x = 10 ; y = 20 ; swap ( & x , & y ) ; cout << x << y ; }
swap ( int * i , int * j ) ;
Example 3
Example 3
Example 4
struct b { int serno ; char text [ 1000 ] ; // A lot of chars } b = { 123, "This is a BIG structure" } ;
void valfunc ( b ) ; // Call by value
void ptrfunc ( * b ) ; // Call by pointer
void reffunc ( & b ) ; // Call by reference Docsity.com
void main ( ) { valfunc ( b ) ; // Passing the variable itself ptrfunc ( & b ) ; // Passing the address of the variable reffunc ( b ) ; // Passing a reference to the variable }
Example 4
Difference Between
References and Pointers
main ( )
{
int i ; int & refi = i ; cout << “The address of the reference is ” << & refi ; cout << & i ;
} Docsity.com