C标准库源码解读(VC9.0版本)——stdarg.h

      stdarg.h中定义处理可变参数函数的方法。我们常用的printf,scanf等函数,都是以此做处理的,平时写代码的时候很少使用到,但是学习多一种方法,明白更多使用方法。其实变参数的实现是通过编译时参数压入栈的位置去查找的。而正确处理需要给出对应的结构类型,因为需要根据结构大小取数据值。明白了这个原理,理解并写处理不定参数的函数并不难。

Variable arguments handling
This header defines macros to access the individual arguments of a list of unnamed arguments whose number and types are not known to the called function.

A function may accept a varying number of additional arguments without corresponding parameter declarations by including a comma and three dots ( ,...) after its regular named parameters:

return_type function_name ( parameter_declarations , ... );
To access these additional arguments the macros va_start, va_arg and va_end, declared in this header, can be used:
  • First, va_start initializes the list of variable arguments as ava_list.
  • Subsequent executions of va_arg yield the values of the additional arguments in the same order as passed to the function.
  • Finally, va_end shall be executed before the function returns.

Types

Macro functions

 

#include <stdarg.h>
#include <assert.h>
/* type definitions */
typedef struct {
	char c;
} Cstruct;


int tryit(char * format,...)
{
	int ctr = 0;
	va_list ap;
	va_start(ap,format);
	while (*format)
	{
		switch(*format)
		{
		case 'i' :
			assert (va_arg(ap, int) == ++ctr);
				break;
		case 'd' :
			assert (va_arg(ap, double) == ++ctr) ;
			break;
		case 'p' :
			assert (va_arg(ap, char *)[0] == ++ctr);
				break;
		case 's' :
			assert (va_arg(ap, Cstruct).c == ++ctr);
		}
	}
	va_end(ap);
	return ctr;
}

int main ()
{
	Cstruct stu;
		stu.c = 'a';
	int k = tryit("dip",1.0,10,"str",stu);
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值