Page 184 - C-Language
P. 184
function to graph into graph().
// A couple of external definitions to make the example clearer
extern unsigned int screenWidth;
extern void plotXY(double x, double y);
// The graph() function.
// Pass in the bounds: the minimum and maximum X and Y that should be plotted.
// Also pass in the actual function to plot.
void graph(double minX, double minY,
double maxX, double maxY,
???? *fn) { // See below for syntax
double stepX = (maxX - minX) / screenWidth;
for (double x=minX; x<maxX; x+=stepX) {
double y = fn(x); // Get y for this x by calling passed-in fn()
if (minY<=y && y<maxY) {
plotXY(x, y); // Plot calculated point
} // if
} for
} // graph(minX, minY, maxX, maxY, fn)
Usage
So the above code will graph whatever function you passed into it - as long as that function meets
certain criteria: namely, that you pass a double in and get a double out. There are many functions
like that - sin(), cos(), tan(), exp() etc. - but there are many that aren't, such as graph() itself!
Syntax
So how do you specify which functions you can pass into graph() and which ones you can't? The
conventional way is by using a syntax that may not be easy to read or understand:
double (*fn)(double); // fn is a pointer-to-function that takes a double and returns one
The problem above is that there are two things trying to be defined at the same time: the structure
of the function, and the fact that it's a pointer. So, split the two definitions! But by using typedef, a
better syntax (easier to read & understand) can be achieved.
Mnemonic for writing function pointers
All C functions are in actuality pointers to a spot in the program memory where some code exists.
The main use of a function pointer is to provide a "callback" to other functions (or to simulate
classes and objects).
The syntax of a function, as defined further down on this page is:
https://riptutorial.com/ 160

