c语言中如何实现不定长参数的宏?

Python053

c语言中如何实现不定长参数的宏?,第1张

宏很难实现变长参数,不过c提供了函数来处理,在c中printf,scanf等函数就是处理变长参数列表的。

如:

#include <stdio.h>

#include <stdarg.h>

void print_ints(int, num_of_args, ...)

{

int total = 0, i

va_list ap

va_start(ap, num_of_args)

while(num_of_arg--){

i = va_arg(ap, int)

printf("%d\n", i)

total += i

}

printf("Total is %d \n", total)

va_end(ap)

}

如果使用

print_int(3, 20, 35, 15)

来调用,则输出:

20

35

15

Total is 70

有关函数:

va_start(argptr, parm) 使用argptr对参数列表和第二个参数parm的名称进行初始化

va_arg(argptr, type) 返回参数表中的下一个参数,它必须包含所指定的type

va_end(argptr) 终止参数读取

arg.a=1000是给arg中的a赋值,parm.a可以说是形参,arg.a可以说是实参,实参和形参的关系你在看看课本吧。return表示中止当前函数的运行,并将操作权返回给调用者。如果是在main函数中,表示将操作权返回给操作系统。return不是必须要返回一个值。

void func(void)

{

......

......

return

}

当然,就算不写return,在函数执行完毕后也会返回操作权给调用者。写return是一种清晰的风格,可以防止一些意外的错误。所以书上只说应该写,而不是必须写。

一个函数的参数的数目没有明确的限制,但是参数过多(例如超过8个)显然是一种不可取的编程风格。参数的数目直接影响调用函数的速度,参数越多,调用函数就越慢。另一方面,参数的数目少,程序就显得精练、简洁,这有助于检查和发现程序中的错误。因此,通常应该尽可能减少参数的数目,如果一个函数的参数超过4个,你就应该考虑一下函数是否编写得当。 如果一个函数不得不使用很多参数,你可以定义一个结构来容纳这些参数,这是一种非常好的解决方法。在下例中,函数print_report()需要使用10个参数,然而在它的说明中并没有列出这些参数,而是通过一个RPT_PARMS结构得到这些参数。 # include <atdio. h>typedef struct ( int orientation char rpt_name[25]char rpt_path[40]int destinationchar output_file[25]int starting_pageint ending_pagechar db_name[25]char db_path[40]int draft_quality)RPT_PARMSvoid main (void)int print_report (RPT_PARMS* )void main (void) { RPT_PARMS rpt_parm/*define the report parameter structure variable * / /* set up the report parameter structure variable to pass to the print_report 0 function */ rpt_parm. orientation = ORIENT_LANDSCAPErpt_parm.rpt_name = "QSALES.RPT"rpt_parm. rpt_path = "Ci\REPORTS" rpt_parm. destination == DEST_FILErpt_parm. output_file = "QSALES. TXT" rpt_parm. starting_page = 1rpt_pann. ending_page = RPT_ENDrpt_pann.db_name = "SALES. DB"rpt_parm.db_path = "Ci\DATA"rpt_pann. draft_quality = TRUE/*call the print_report 0 functionpaaaing it a pointer to the parameteM inatead of paMing it a long liat of 10 aeparate parameteM. * / ret_code = print_report(cu*pt_parm)} int print_report(RPT_PARMS*p) { int rc/*acccM the report parametcra paaaed to the print_report() function */ oricnt_printcr(p->orientation)Kt_printer_quality((p->draft_quality == TRUE) ? DRAFT NORMAL)return rc} 上例唯一的不足是编译程序无法检查引用print_report()函数时RPT_PARMS结构的10个成员是否符合要求。