Next: Function names returning Up: Procedures Previous: Procedures

Form of a function definition

The general syntax in ANSI C is:

type name (argument definitions)
   {
   local definitions
   statements
   }

In fact much of this is optional: a minimum function definition is

   dummy(){}

which does nothing. Even this is useful, as a placeholder during program development, although usually with a meaningful name and comments!

A function is invoked/called by writing its name, with suitable arguments, in an executable body of code.

Example

Here is a simple, complete program incorporating a function.

int main()
{
int var1, var2;

var1= 23;  var2= -12;

print_smaller(var1,var2);   /* call the function */
                            /* i.e. get it executing */

/* Nothing more to do, so finish here */
}

/* This routine prints out the smaller of its two arguments */
void print_smaller   /* define the function i.e. say what it does */
   (
   int first,   /* first number to be compared */
   int second   /* second number to be compared */
   )
{
if (first < second)
   printf("%d\n",first);
else
   printf("%d\n",second);
}

Notes

1. The function has a name, like a variable has. Soon we will see that it can also have a value.

2. There is no semi-colon after the argument list. (This is the same for main()).

3. The types of the arguments should be defined.

4. The body of the function is a block. (This is the same for main()).

5. The function application usually has the same number and types of arguments as its definition.

6. In C, arguments are always passed by value. This allows such usages as:

   print_smaller(var1*10, var2 + 6);

because the arguments are evaluated before the result is passed into the function.

7. Once a function has been defined, it can of course be used many times, with various arguments.

   print_smaller(10,20);
   print_smaller(var1 + var2, var1*var2);

8. A program can have any number of functions, each with its unique name, but only one main.

9. In C, you may not define functions inside other functions.



Next: Function names returning Up: Procedures Previous: Procedures


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