Sams Teach Yourself C in 21 Days

(singke) #1
29: ptr = one;
30: else if (nbr == 2)
31: ptr = two;
32: else
33: ptr = other;
34: func1(ptr);
35: }
36: return 0;
37: }
38:
39: void func1(void (*p)(void))
40: {
41: p();
42: }
43:
44: void one(void)
45: {
46: puts(“You entered 1.”);
47: }
48:
49: void two(void)
50: {
51: puts(“You entered 2.”);
52: }
53:
54: void other(void)
55: {
56: puts(“You entered something other than 1 or 2.”);
57: }

Enter an integer between 1 and 10, 0 to exit:
2
You entered 2.
Enter an integer between 1 and 10, 0 to exit:
11
You entered something other than 1 or 2.

Enter an integer between 1 and 10, 0 to exit:
0
Notice the differences between Listing 15.9 and Listing 15.10. The declaration of
the pointer to a function has been moved to line 18 in main(), where it is needed.
Code in main()now initializes the pointer to point to the correct function, depending on
the value the user entered (lines 26 through 33), and then passes the initialized pointer to
func1().func1()really serves no purpose in Listing 15.10; all it does is call the func-
tion pointed to by ptr. Again, this program is for illustration purposes. The same princi-
ples can be used in real-world programs, such as the example in the next section.

412 Day 15

LISTING15.10 continued

INPUT/
OUTPUT

ANALYSIS

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

Free download pdf