Sams Teach Yourself C in 21 Days

(singke) #1
Pointers: Beyond the Basics 411

15


You entered something other than 1 or 2.
Enter an integer between 1 and 10, 0 to exit:
0
This program employs an infinite loop starting on line 16 to continue execution
until a value of 0 is entered. When a nonzero value is entered, it’s passed to
func1(). Note that line 32, in func1(), contains a declaration for a pointer ptrto a func-
tion. Being declared within a function makes ptrlocal to func1(), which is appropriate
because no other part of the program needs access to it. func1()then uses this value to
setptrequal to the appropriate function (lines 34 through 39). Line 41 then makes a sin-
gle call to ptr(), which calls the appropriate function.
Of course, this program is for illustration purposes only. You could have easily accom-
plished the same result without using a pointer to a function.
Now you can learn another way to use pointers to call different functions: passing the
pointer as an argument to a function. Listing 15.10 is a revision of Listing 15.9.

LISTING15.10 passptr.c. Passing a pointer to a function as an argument
1: /* Passing a pointer to a function as an argument. */
2:
3: #include <stdio.h>
4:
5: /* The function prototypes. The function func1() takes as */
6: /* its one argument a pointer to a function that takes no */
7: /* arguments and has no return value. */
8:
9: void func1(void (*p)(void));
10: void one(void);
11: void two(void);
12: void other(void);
13:
14: int main( void )
15: {
16: /* The pointer to a function. */
18: void (*ptr)(void);
19: int nbr;
20:
21: for (;;)
22: {
23: puts(“\nEnter an integer between 1 and 10, 0 to exit: “);
24: scanf(“%d”, &nbr);
25:
26: if (nbr == 0)
27: break;
28: else if (nbr == 1)

ANALYSIS

INPUT

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

Free download pdf