Introduction to User-defined functions in C++

C++ allows programmers to define their own functions. For example the
following is a definition of a function which given the
co-ordinates of a point `(x,y)`

will return its distance from the
origin.

float distance(float x, float y) // Returns the distance of (x, y) from origin { float dist; //local variable dist = sqrt(x * x + y * y); return dist; }

Download program.This function has two input parameters, real values

`x`

and `y`

,
and returns the distance of the point `(x,y)`

from the
origin. In the function a `dist`

is used to temporarily hold the calculated value inside the
function.
The general form of a function definition in C++ is as follows:

function-type function-name`(`

parameter-list`)`

`{`

local-definitions`;`

function-implementation`;`

`}`

- If the function returns a value then the type of that value must be
specified in
*function-type*. For the moment this could be`int`

,`float`

or`char`

. If the function does not return a value then the*function-type*must be`void`

. - The
*function-name*follows the same rules of composition as identifiers. - The
*parameter-list*lists the formal parameters of the function together with their types. - The
*local-definitions*are definitions of variables that are used in the*function-implementation*. These variables have no meaning outside the function. - The
*function-implementation*consists of C++ executable statements that implement the effect of the function.

- Functions with no parameters
- Functions with parameters and no return value
- Functions that return values
- Example function: sum of squares of integers
- Example Function: Raising to the power
- Call-by-value parameters
- Summary
- Review Questions
- Exercises

1999-08-31