C Functions

Programmer Defined Functions

Function Prototypes

Prototypes are function headers without bodies (similar to method declarations in Java interfaces). They let the compiler know a function exists so we can use it without the definition having yet appeared. They serve as code specifications as well, so the compiler knows what a legal call looks like and another programmer knows how that function should be defined.

Function Definitions

The general format is return_type fun_name(arg_type_1 var_1, arg_type_2 var_1, etc), for example int randInt(int a, int b).

Where can they go?

Return type return_type

Parameter list format:

Function call format

Program Structure and Compilation

Generally we want to separate function declarations (prototypes) from their definitions into two related files.

Preprocessor directives

The #include directive is used for both language libraries and programmer defined function header files. See also the next section on Compilation for other pre-processor options.

Compilation

#ifndef MY_FUNCS_H // MYFUNCS_H is a flag for the my_funcs.h header file
#define MY_FUNCS_H // define it if its undefined, and load it
// function prototypes go here
#endif // if the flag was previously defined, no headers loaded

Object files

make and Makefiles

We use a tool called make along with a special type of file called a Makefile to keep track of all the parts of a program and define their dependences and rules for separate compilation and linking.

The Unix make program does the making.

% make
gcc -std=c99 -pedantic -Wall -Wextra -O -g   -c -o my_main.o my_main.c
gcc -std=c99 -pedantic -Wall -Wextra -O -g   -c -o my_funcs.o my_funcs.c
gcc   my_main.o my_funcs.o   -o program
% make
make: `my_main' is up to date.
% touch my_main.c 
% make
gcc -std=c99 -pedantic -Wall -Wextra -O -g   -c -o my_main.o my_main.c
gcc my_main.o my_funcs.o -o program
%

Library Functions

Below are some commonly used function libraries in C. Also see Notes on I/O library (stdio.h), characters (ctype.h) and string (string.h).

Assert

Assertions are particularly useful in functions to check the validity of parameter values. When an assertion fails, the program will stop running. If it passes (results in true), then the program keeps going.

Math

The math library has many useful functions. These generally have double arguments and return double values.

Random numbers

The built-in library is very limited, but we can manipulate the results with some common arithmetic expressions to generate different types and ranges of values. Below are a few examples. We usually explicit "seed" the random generator to generate a new starting value and resulting "random" sequence each time the program is run.