Cpp - Function Function Definition

Introduction

A function has a name and a type.

The function's type is defined by its return value.

When a function is declared, you have to provide the following information for the compiler

  • the name and type of the function and
  • the type of each argument.

They are referred to as the function prototype. Examples:

int toupper(int); 
double pow(double, double); 

This informs the compiler that the function toupper() is of type int, i.e. its return value is of type int.

And it expects an argument of type int.

The second function pow() is of type double and two arguments of type double must be passed to the function when it is called.

The types of the arguments may be followed by names which can be changed later in the function definition.

int toupper(int c); 
double pow(double base, double exponent); 

From the compiler's point of view, these prototypes are equivalent to the prototypes in the previous example.

Functions without Return Value

You can write functions that perform a action but do not return a value.

The type void is available for functions of this type. For example,

void srand( unsigned int seed ); 

Functions without Arguments

If a function does not expect an argument, the function prototype must be declared as void or empty braces.

Example:

int rand( void );      

or

int rand(); 

Related Topics

Example

Exercise