Next: A brief digression Up: Procedures Previous: Form of a

Function names returning a value

The function name can be used to return a value.

Example

We might write:

int main()
{
int var1, var2;

var1= 23;  var2= -12;
printf("%d\n", smaller(var1,var2) );
}

/* This routine returns the value of the smaller of its two arguments */
int smaller
   (
   int first,   /* first number to be compared */
   int second   /* second number to be compared */
   )
{
if (first < second)
   return first;
else
   return second;
}

Notes

w1. The type of the function should be defined: it can be any type. In this case we have defined it to be int. (C assumes int by default, but better not to take advantage of this. If you do not want to return a value, define it to be type void).

2. The return statement causes an immediate exit back to the statement following the invocation, and the value is that given by the associated expression. The syntax is:

     return expression;

The expression may be a constant, a simple variable or a general expression. The value of the epression is calculated and then, if necessary, converted to the type named in the first line of the function.

3. There can be any number of return statements in a function.

4. A void function can also make use of return statements: just use return; without a following expression.

5. If a function has no return statement, then it returns when it runs out of things to do. i.e. at the end of its outer block.

6. This program is a better solution than the previous one: in the second version you can decide in main what to do with the smaller value. In the first one you had to print it out and main never saw the answer.

Exercise

Write a function which returns `true' if the first argument is smaller than the second; otherwise it returns `false'.

Use it in an if statement to control the printing of one or other of the arguments.



Next: A brief digression Up: Procedures Previous: Form of a


maspjw@
Tue Sep 27 15:29:34 BST 1994