[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Memory Allocation Up: Review Previous: Functions

Declarations

First, a note on terminology. A variable is defined when it is created, and space is made for it. A variable is declared when it already exists but needs to be re-described to the compiler (perhaps because it was defined in another source file). Think of declaring in C++ like declaring at customs - admitting to the existence of something. In C++ you can only define a variable once but you can declare it many times.

C++ declarations are not easy to read. You shouldn't need to use complicated declarations so don't worry too much if you can't `decode' them. Keep a cribsheet of useful ones The following examples show common declarations.

int *p pointer to an int
int x[10] an array of 10 ints
const int *p pointer, p, to int; int can't be modified via p
int * const p a constant pointer to an int
int (*x)[10] a pointer to an array of 10 ints
int *x[10] array of 10 pointers to ints
int (*f)(int) pointer to a function taking and returning an int
void (*f)(void) pointer to a function taking no args and returning nothing
int (*f[])(int) An array of pointers to a functions taking and returning an int

Note the importance of the brackets in these declarations. On the Teaching System the c++decl program can help. E.g.

   c++decl explain "char *&x"

prints

   declare x as reference to pointer to char

typedef can be used to create a shorthand notation for a verbose type.

typedef int (*PFI)(int) // declare PFI as pointer to function that 
                        //   takes and returns an int.
PFI f[];  // declare f as an array of pointers of type 'PFI'.


next up previous contents
Next: Memory Allocation Up: Review Previous: Functions
Tim Love
2001-07-05