[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Declarations Up: Review Previous: Pointers

Functions

The form of a function definition is
<function return type> <function name> ( <formal argument list> )
{
<local variables>

<body>

}

E.g.

int mean(int x, int y)
{
int tmp;

tmp = (x + y)/2;
return tmp;
}

or, if the function is a member of class stats, ::, the scope resolution operator can be used to specify which particular function of that name to access.

int stats::mean(int x, int y)
{
int tmp;

tmp = (x + y)/2;
return tmp;
}

You can provide default values for the trailing arguments. E.g.

int mean(int x, int y=5)
{
int tmp;

tmp = (x + y)/2;
return tmp;
}

...
int foo=mean(7)

is legal, setting foo to 6.

You can have more than function of a particular name provided that the compiler knows unambiguously which one is required for a function call, so the functions with identical names have to take different arguments or must only be visible one at a time. It's not enough for functions to differ only in the return type. By default, the variables given to a function won't have their values changed when the function returns. In the following fragment number won't be increased to 6.

void add (int x)
{
  x = x+1;
}

int number = 5;
add(number);

When add(number) is called, the x variable is set to the current value of number, then incremented, but number is unchanged. The following slight variation that uses ``call by reference'' will increase number

void add(int& x)
{
  x = x+1;
}

int number = 5;
add(number);


next up previous contents
Next: Declarations Up: Review Previous: Pointers
Tim Love
2001-07-05