Sams Teach Yourself C in 21 Days

(singke) #1
float square(float x); // The function prototype.
float (*ptr)(float x); // The pointer declaration.
float square(float x) // The function definition.
{
return x * x;
}
Because the function square()and the pointer ptrhave the same parameter and return
types, you can initialize ptrto point to squareas follows:
ptr = square;
You can then call the function using the pointer as follows:
answer = ptr(x);
It’s that simple. For a real example, compile and run Listing 15.8, which declares and
initializes a pointer to a function and then calls the function twice, using the function
name the first time and the pointer the second time. Both calls produce the same result.

LISTING15.8 ptr.c. Using a pointer to a function to call the function
1: /* Demonstration of declaring and using a pointer to a function.*/
2:
3: #include <stdio.h>
4:
5: /* The function prototype. */
6:
7: double square(double x);
8:
9: /* The pointer declaration. */
10:
11: double (*ptr)(double x);
12:
13: int main( void )
14: {
15: /* Initialize p to point to square(). */
16:
17: ptr = square;
18:
19: /* Call square() two ways. */
20: printf(“%f %f\n”, square(6.6), ptr(6.6));
21: return 0;
22: }
23:
24: double square(double x)
25: {
26: return x * x;
27: }

408 Day 15

INPUT

25 448201x-CH15 8/13/02 11:13 AM Page 408

Free download pdf