Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 409

15


OUTPUT 43.560000 43.560000

Precision of the values might cause some numbers to not display as the
exact values entered. For example, the correct answer, 43.56, might appear
as 43.559999.

Note


Line 7 declares the function square(), and line 11 declares the pointer ptrto a function
containing a doubleargument and returning a doublevalue, matching the declaration of
square(). Line 17 sets the pointer ptrequal to square. Notice that parentheses aren’t
used with squareorptr. Line 20 prints the return values from calls to square()and
ptr().
A function name without parentheses is a pointer to the function (sounds similar to the
situation with arrays, doesn’t it?). What’s the point of declaring and using a separate
pointer to the function? Well, the function name itself is a pointer constant and can’t be
changed (again, a parallel to arrays). A pointer variable, in contrast, can be changed.
Specifically, it can be made to point to different functions as the need arises.
Listing 15.9 calls a function, passing it an integer argument. Depending on the value of
the argument, the function initializes a pointer to point to one of three other functions
and then uses the pointer to call the corresponding function. Each of these three func-
tions displays a specific message on-screen.

LISTING15.9 ptr2.c. Using a pointer to a function to call different functions
depending on program circumstances
1: /* Using a pointer to call different functions. */
2:
3: #include <stdio.h>
4:
5: /* The function prototypes. */
6:
7: void func1(int x);
8: void one(void);
9: void two(void);
10: void other(void);
11:
12: int main( void )
13: {
14: int nbr;
15:

INPUT

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

Free download pdf