Lecture Notes for Introduction to Computer Science II
2 August 2001 - Pointers and Functions
- argument passing revisited
- parameter changes made inside don't show up outside
- formal and actual parameters occupy different parts of memory
- changes made in one place don't appear in the other place, and vice
versa
- passing values through parameters using pointers
- isolated changes are not fatal, but it's a pain
- to have inside changes appear outside, both places have to be the same,
and equal to the outside place
- pointers can solve this problem - pass the address of the outside place
into the function; side can now change the outside place
- passing pointers in parameters is known as call by reference
- pointer parameters work, but are clumsy
- must remember to proceed actual arguments with the address-of
operator
&
- can't pass expressions because they don't have addresses
- formal pointer parameters must be proceeded by the follow-address
operator
*
- passing values through parameters not using pointers
- c++ provides a mechanism for true call-by-reference parameters
- if T is a type, then T
&
is the type reference to T
-
void f(int i)
vs. void f(int & i)
- a reference parameter has the same address as the actual parameter
- it is not necessary to precede the actual parameter with
&
-
expressions are still illegal (sorta)
- it is not necessary to precede the formal reference parameter with
*
- it is a compile-time error;
- using the const modifier
- pointer and reference parameters are efficient - copying 4 or 8 bytes
vs. copying 100s or 1000s of bytes
- but they are also unsafe because of propagating changes
- the
const
declaration modifier helps by preventing inside changes
- const pointer parameters
- two things can be constant - the pointer value and the value pointed
to; usually want the value pointed to to be constant
- the trick is to read the type declaration from right to left
-
T * const x
- x
is a constant pointer to T value
-
const T * x
- x
is a pointer to a T value constant
-
const T * const x
- x
is a constant pointer to a T value
constant
-
T * const x
is not so important - prevents the function from
changing the value of x; constants are easier than variables to
understand; enables possible compiler optimizations
- cde9const T * x) is important - prevents the function from changing
the value of what
x
points to
- const reference parameters
- because references are already constants, using const with them is
easier than with pointers
- const reference parameters are fast and safe
-
const T & x
- returning pointer or references values from functions
- values local to a function disappear once the function returns
- pointers and references to those values are useless after the function
returns
-
int * f(void) {
int i;
return &i;
}
This page last modified on 2 August 2001.