





















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!






















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