Docsity

Understanding Reference Variables and Call-by-Reference in C++, Slides of Data Structures and Algorithms

Partial preview of the text

Download Understanding Reference Variables and Call-by-Reference in C++ and more Slides Data Structures and Algorithms in PDF only on Docsity!

 The symbol “&” has a few different purposes depending on where it occurs in code.

 When it appears in front of a variable name, it is the address operator, i.e., it returns the address of the variable in memory.

int x; int ptr = &x;*

 The symbol “&’ can also appear after a type in a function signature:

 For example, insert and remove from the BinarySearchTree class.

void insert( const EType& x ); void remove( const EType& x );

 The “&” indicates a parameter that is a

reference variable.

 Consider the following three different

functions:

// example 1

int intMinus1( int oldVal)

{

oldVal = oldVal – 1; return oldVal;

}

// example 3

int intMinus3( int& oldVal)

{

oldVal = oldVal – 3; return oldVal;

}

The caller function: calling intMinus

void caller()

{

int myInt = 31; int retVal; retVal = intMinus1( myInt ); cout << myInt << retVal;

}

 Call stack layout

Parameters(caller) Local variables(caller) Return address(caller) Parameters(intMinus1) Local variables(intMinus1) Return address(intMinus1) sp

Stack grows downwards

Call stack layout when intMinus1 is called:

1052

1060

1068

1056

1072 31 ? caller’s other stuff

myInt retVal

31 oldVal

calling function “caller”

called function “intMinus1”

stack grows downwards

sp

 The original myInt remains

unchanged.

 For this reason, this technique of

passing parameters is called pass by

value.

 Alterations are done to the copy of “31”

(stored in oldVal) and not the original

myInt.

Call stack layout after subtraction in intMinus1:

1052

1060

1068

1056

1072 31 ? caller’s other stuff

myInt retVal

31 oldVal

calling function “caller”

called function “intMinus1”

stack grows downwards

sp

30

 We could have called intMinus1 as void caller() { int retVal; retVal = intMinus1( 31 );// literal cout << myInt << retVal; }

 Because it is the value that is passed. We can always pass a literal or even an expression in call-by-value.

 If the programmer wanted to actually change a variable’s value from within a function, one way would be to send a pointer: void caller() { int retVal; int myInt = 31; retVal = intMinus2( &myInt ); cout << myInt << retVal; }

 Call this call-by-pointer.

Call stack layout after **oldVal = oldVal – 2;

1052

1060

1068

1056

1072 31 ? caller’s other stuff

myInt retVal

1072 oldVal

calling function “caller”

called function “intMinus2”

stack grows downwards

sp

29

Call stack layout after return from intMinus2.

1068

1072 31 29 caller’s other stuff

myInt retVal calling function “caller”

stack grows downwards

sp

29