{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# CS201-30 - Introduction to Programming Lecture 30 In...

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Introduction to Programming Lecture 30 In Today’s Lecture – References References – Differences Between References and Pointers Reference & int & i ; ‘i’ is a reference to an integer int * i ; ‘i’ is a pointer to an integer int i ; int & j = i ; main ( ) { int i ; int & j = i ; i = 123 ; cout << i << endl ; cout << j << endl ; i++ ; cout << i << endl ; cout << j ; } Example 1 Output 123 123 124 124 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 ; } Example 2 main ( ) { int x , y ; x = 10 ; y = 20 ; swap ( & x , & y ) ; cout << x << y ; } Example 2 swap ( int * i , int * j ) ; void swap ( int * i , int * j ) { int * temp = i ; * i = * j ; * j = * temp ; } Example 2 void swap ( int & i , int & j ) { int temp = i ; i = j ; j = temp ; } Example 3 Example 3 main ( ) main ( ) { int x , y ; x = 10 ; y = 20 ; swap ( x , y ) ; cout << x << y ; } const 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 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 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 ( const * b ) ; // Call by pointer void reffunc ( const & b ) ; // Call by reference Example 4 Difference Between References and Pointers main ( ) { int i ; int & refi = i ; cout << “The address of the reference is ” << & refi ; cout << & i ; } Dangling Reference int mynum = 0 ; // Global variable int & num ( ) { return mynum ; } void main ( ) { int i ; mynum = 100 ; i = num ( ) ; num ( ) = 200 ; } References as Return Values int & i ; double & f ; char & c ; a = b = c ; a = b ; cout << “The values of the integer is ”<< i << endl ; ...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online