Graphics Programs Reference
In-Depth Information
0x244
Functions
Sometimes there will be a set of instructions the programmer knows he will
need several times. These instructions can be grouped into a smaller sub-
program called a function . In other languages, functions are known as sub-
routines or procedures. For example, the action of turning a car actually
consists of many smaller instructions: Turn on the appropriate blinker, slow
down, check for oncoming traffic, turn the steering wheel in the appropriate
direction, and so on. The driving directions from the beginning of this chap-
ter require quite a few turns; however, listing every little instruction for every
turn would be tedious (and less readable). You can pass variables as arguments
to a function in order to modify the way the function operates. In this case,
the function is passed the direction of the turn.
Function Turn(variable_direction)
{
Activate the variable_direction blinker;
Slow down;
Check for oncoming traffic;
while(there is oncoming traffic)
{
Stop;
Watch for oncoming traffic;
}
Turn the steering wheel to the variable_direction;
while(turn is not complete)
{
if(speed < 5 mph)
Accelerate;
}
Turn the steering wheel back to the original position;
Turn off the variable_direction blinker;
}
This function describes all the instructions needed to make a turn. When
a program that knows about this function needs to turn, it can just call this
function. When the function is called, the instructions found within it are
executed with the arguments passed to it; afterward, execution returns to
where it was in the program, after the function call. Either left or right can
be passed into this function, which causes the function to turn in that
direction.
By default in C, functions can return a value to a caller. For those
familiar with functions in mathematics, this makes perfect sense. Imagine a
function that calculates the factorial of a number—naturally, it returns the
result.
In C, functions aren't labeled with a “function” keyword; instead, they
are declared by the data type of the variable they are returning. This format
looks very similar to variable declaration. If a function is meant to return an
Search WWH ::




Custom Search