Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help
next up previous contents
Next: Pointers Up: ANSI C for Programmers Previous: Contractions   Contents

Functions

C has no procedures, only functions. Their definitions can't be nested but all except main can be called recursively. In ANSI C the form of a function definition is
function type function name ( formal argument list )
{
local variables

body

}

E.g.

int mean(int x, int y)
{
int tmp;

tmp = (x + y)/2;
return tmp;
}

In K&R C the same function would be written as

int mean(x,y)
int x;
int y;
{
int tmp;

tmp = (x + y)/2;
return tmp;
}

Note that the formal argument declarations are differently placed. This are the most visible difference between ANSI C and K&R C . Programs (usually called protoize or protogen) exist to convert to ANSI C style argument declarations.

The default function type is `extern int' and the default type for the formal arguments is `int' but depending on these defaults is asking for trouble; they should be explicitly declared.

Functions end when

Just as return can return a value to the calling routine, so exit returns a value to the Unix environment. By convention, returning a zero means that the program has run successfully. Better still, return EXIT_SUCCESS or EXIT_FAILURE; they're defined in stdlib.h.

All parameters in C are `passed by value'. To perform the equivalent of Pascal's `pass by reference' you need to know about pointers.


next up previous contents
Next: Pointers Up: ANSI C for Programmers Previous: Contractions   Contents
Tim Love 2010-04-27