Node:Functions with values, Next:, Previous:Function examples, Up:Functions



Functions with values

In mathematics, a function takes one or more values and calculates, or returns, another value. In C, some functions return values and others do not; whether a function you write does or does not will depend on what you want the function to do. For example, a function that calculates a value should probably return that value, while a function that merely prints something out may not need to.

The add_two_numbers function above did not return a value. We will now examine a function that does.

Here is an example of calling a function that returns a value:

bill = calculate_bill (data1, data2, data3);

When this statement is executed, control is passed to the function calculate_bill, that function executes, and then it returns control and some value to the original statement. The value returned is assigned to bill, and the program continues.

In C, returning a value from a function is a simple matter. Consider the function calculate_bill as it might be written in a program that contains the statement above:

int calculate_bill (int a, int b, int c)
{
  int total;

  total = a + b + c;
  return total;
}

As soon as the return statement is met, calculate_bill stops executing and returns the value total.

A function that returns a value must have a return statement. Forgetting it can ruin a program. For instance if calculate_bill had read as follows, then the variable bill would have had no meaningful value assigned to it, and you might have received a warning from the compiler as well. (The word void below indicates that the function does not return a value. In ANSI C, you must place it before the name of any such function.)

void calculate_bill (int a, int b, int c)
{
  int total;

  total = a + b + c;
}

On the other hand, you do not need to actually use a value when a function returns one. For example, the C input/output functions printf and scanf return values, but the values are rarely used. See output, for more information on these functions.

If we use the first version of the calculate_bill function (the one that contains the line return total;), the value of the function can simply be discarded. (Of course, the resulting program is not very useful, since it never displays a value to the user!)

int main()
{
  calculate_bill (1, 2, 3);
  exit (0);
}