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



Function prototyping

Functions do not have to return integer values, as in the above examples, but can return almost any type of value, including floating point and character values. (See Variables and declarations, for more information on variable types.)

A function must be declared to return a certain variable type (such as an integer), just as variables must be. (See Variables and declarations, for more information about variable types.) To write code in good C style, you should declare what type of value a function returns (and what type of parameters it accepts) in two places:

  1. At the beginning of the program, in global scope. (See Scope.)
  2. In the definition of the function itself.

Function declarations at the beginning of a program are called prototypes. Here is an example of a program in which prototypes are used:

#include <stdio.h>

void print_stuff (int foo, int bar);
int calc_value (int bas, int quux);


void print_stuff (int foo, int bar)
{
  int var_to_print;

  var_to_print = calc_value (foo, bar);
  printf ("var_to_print = %d\n", var_to_print);
}


int calc_value (int bas, int quux)
{
  return bas * quux;
}


int main()
{
  print_stuff (23, 5);
  exit (0);
}

The above program will print the text var_to_print = 115 and then quit.

Prototypes may seem to be a nuisance, but they overcome a problem intrinsic to compilers, which is that they compile functions as they come upon them. Without function prototypes, you usually cannot write code that calls a function before the function itself is defined in the program. If you place prototypes for your functions in a header file, however, you can call the functions from any source code file that includes the header. This is one reason C is considered to be such a flexible programming language.

Some compilers avoid the use of prototypes by making a first pass just to see what functions are there, and a second pass to do the work, but this takes about twice as long. Programmers already hate the time compilers take, and do not want to use compilers that make unnecessary passes on their source code, making prototypes a necessity. Also, prototypes enable the C compiler to do more rigorous error checking, and that saves an enormous amount of time and grief.