Graphics Programs Reference
In-Depth Information
integer (perhaps a function that calculates the factorial of some number x ),
the function could look like this:
int factorial(int x)
{
int i;
for(i=1; i < x; i++)
x *= i;
return x;
}
This function is declared as an integer because it multiplies every value
from 1 to x and returns the result, which is an integer. The return statement
at the end of the function passes back the contents of the variable x and ends
the function. This factorial function can then be used like an integer variable
in the main part of any program that knows about it.
int a=5, b;
b = factorial(a);
At the end of this short program, the variable b will contain 120, since
the factorial function will be called with the argument of 5 and will return 120.
Also in C, the compiler must “know” about functions before it can use
them. This can be done by simply writing the entire function before using it
later in the program or by using function prototypes. A function prototype is
simply a way to tell the compiler to expect a function with this name, this
return data type, and these data types as its functional arguments. The actual
function can be located near the end of the program, but it can be used any-
where else, since the compiler already knows about it. An example of a func-
tion prototype for the factorial() function would look something like this:
i nt factorial(int);
Usually, function prototypes are located near the beginning of a program.
There's no need to actually define any variable names in the prototype, since
this is done in the actual function. The only thing the compiler cares about is
the function's name, its return data type, and the data types of its functional
arguments.
If a function doesn't have any value to return, it should be declared as void ,
as is the case with the turn() function I used as an example earlier. However,
the turn() function doesn't yet capture all the functionality that our driving
directions need. Every turn in the directions has both a direction and a street
name. This means that a turning function should have two variables: the
direction to turn and the street to turn on to. This complicates the function
of turning, since the proper street must be located before the turn can be
made. A more complete turning function using proper C-like syntax is listed
below in pseudo-code.
Search WWH ::




Custom Search