《C和指針》第7章第4道編程題:
編寫一個名叫max_list的函數,它用於檢查任意數目的整型參數並返回它們中的最大值。參數列表必須以一個負值結尾,提示列表的結束。
1 /*
2 ** 查找任意數目的整型參數中的最大值
3 */
4
5 #include <stdio.h>
6 /*
7 ** 要實現可變參數列表,需要包含stdarg.h文件
8 ** stdarg.h中聲明了va_list, va_start, va_arg 和 va_end
9 */
10 #include <stdarg.h>
11
12 int max_list( int n, ... );
13
14 int
15 main()
16 {
17 printf( "%d", max_list( 10, 23, 89, 56, 83, 91, 100, -1) );
18 }
19
20 /*
21 ** 接受任意個正整數,返回最大值
22 ** 參數列表必須以負值結尾,提示列表的結束
23 */
24 int
25 max_list( int n, ... )
26 {
27 va_list val;
28 int max = 0;
29 int i;
30 int current;
31
32 /*
33 ** 准備訪問可變參數
34 */
35 va_start( val, n );
36
37 /*
38 ** 取出可變列表中的值
39 ** 負值提示列表結束
40 */
41 while( ( current = va_arg( val, int ) ) >= 0 )
42 {
43 if( max < current )
44 max = current;
45 }
46
47 /*
48 ** 完成處理可變列表
49 */
50 va_end( val );
51
52 return max;
53 }