Generating the value in a function

Within the local actions of a function which returns a value, at least one return statement must be present. It consists of the keyword return followed by an expression of the type that is specified for the function. Reaching a return statement in a function means that the functions's actions are complete, following its call, and the value generated is that given in the return statement.

It is quite legal to have more than one return statement in the body of a function. This is usually done to allow different branches of an if else statement or cases within a switch to return alternative values.

It is essential to make sure that every possible outcome of a function leads to a return statement generating a value of correct type. Any good compiler will generate an error message if there is a route through the function which allows it to end without generating the required value.

Here is an example of a function which has two return statements. The one that takes effect depends on the outcome of the condition following the if.

int greater(int v1, int v2)
{
   if (v1> v2) return v1;
   return v2;
}
For functions which do not generate a value, the type specified in the header is void which means that no return statement is required. They optionally use a return with no value given.
void out2(int v1, int v2)
{
   printf("%d, %d", v1, v2);
   return;
}

Exercises on this section.


Next - Calling functions.

Back to Contents page.