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
{
local variables
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
- execution reaches the closing `}' of the function. If the function is supposed to return something, the return value will be undefined.
- a `return' statement is reached, returning control to the calling function.
- an `exit' statement is reached, ending execution of the whole program.
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.