Functions
Most languages allow you to create functions of some sort. Functions
let you chop up a long program into named sections so that the sections
can be reused throughout the program. Functions accept parameters and return
a result. C functions can accept an unlimited number of parameters. In
general, C does not care in what order you put your functions in the
program, so long as a the function name is known to the compiler before
it is called.
We have already talked a little about functions. The rand function seen previously is about as simple as a function can get. It accepts no parameters and returns an integer result:
int rand()
/* from K&R
- produces a random number between 0 and 32767.*/
{
rand_seed = rand_seed * 1103515245 +12345;
return (unsigned int)(rand_seed / 65536) % 32768;
}
The int rand() line declares the function
rand to the rest of the program and specifies that rand will accept no
parameters and return an integer result. This function has no local
variables, but if it needed locals, they would go right below the
opening { (C allows you to declare variables after any { -- they exist until the program reaches the matching } and then they disappear. A function's local variables therefore vanish as soon as the ma
...
Read more »