Function return types


As we showed in our previous tutorial, a function calling function may or may not return any values. If it is, it is done through the return statement. While it is possible to send any number of values to the calling function for information, the calling function can only return one value to the maximum call.

The return statement may take one of the following forms:

return;
or
return (expression);

First, the 'plain' return gives no value; It acts as the closing bracket for the function. When a return is encountered, the control immediately returns to the calling function. Examples of common return uses are:

if(err)
 return;

The second form of return with expression provides the value of the expression. For example, function

int sum(int a, int b)
{
  int s;
  s = a + b;
  return s;
}

returns the value of 's' which is the summation of the values of a and b. The last two statements can be combined into one statement as follows :

int sum(int a, int b)
{
  return (a + b);
}

A function can have multiple return statements. This condition occurs when the expected value is subject to certain conditions. For example:

if(a > b)
  return a;
else
  return b;

What type of data does a function return?

All functions by default return int type data.

But what happens if a function must return some other type?

We can force a function to return a particular type of data by using a type specifier in the function header as discussed earlier.

When a value is returned, it is automatically cast to the function's type. In functions that do computations using doubles, yet return int, the returned value will be truncated to an integer. For instance, the function

int Sum()
{
  return (1.6 + 3.8);
}
// this function will return the value 5.