Docsity

Introduction to Programming Lecture 30: References vs Pointers, Slides of Computer Programming

Partial preview of the text

Download Introduction to Programming Lecture 30: References vs Pointers and more Slides Computer Programming in PDF only on Docsity!

Introduction to Programming

Lecture 30

In Today’s Lecture

  • References
  • Differences

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 ) ;

void swap ( int & i , int & j )

int temp = i ;

i = j ;

j = temp ;

Example 3

Example 3

main ( )

int x , y ;

x = 10 ;

y = 20 ;

swap ( x , y ) ;

cout << x << y ;

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