对于C语言中printf这样的函数,参数个数不固定,类型也不固定,用重载是很难实现的。查了下printf函数的原型:_CRTIMP int __cdecl printf(const char *, ...);看到一个...。这是我第二次看到...,第一次是异常处理中用来捕获所有异常。想想也真惭愧,学C这么多年了,居然不晓得函数定义时还可以用这东西。
查了关于变长参数的相关资料,原来C语言中如果函数的参数信息不定,可以用...申明。查了下MSDN,发现下面代码:
/* VA.C: The program below illustrates passing a variable
* number of arguments using the following macros:
* va_start va_arg va_end
* va_list va_dcl (UNIX only)
*/
#include <stdio.h>
#define ANSI /* Comment out for UNIX version */
#ifdef ANSI /* ANSI compatible version */
#include <stdarg.h>
int average( int first, ... );
#else /* UNIX compatible version */
#include <varargs.h>
int average( va_list );
#endif
void main( void )
{
/* Call with 3 integers (-1 is used as terminator). */
printf( "Average is: %d/n", average( 2, 3, 4, -1 ) );
/* Call with 4 integers. */
printf( "Average is: %d/n", average( 5, 7, 9, 11, -1 ) );
/* Call with just -1 terminator. */
printf( "Average is: %d/n", average( -1 ) );
}
/* Returns the average of a variable list of integers. */
#ifdef ANSI /* ANSI compatible version */
int average( int first, ... )
{
int count = 0, sum = 0, i = first;
va_list marker;
va_start( marker, first ); /* Initialize variable arguments. */
while( i != -1 )
{
sum += i;
count++;
i = va_arg( marker, int);
}
va_end( marker ); /* Reset variable arguments. */
return( sum ? (sum / count) : 0 );
}
#else /* UNIX compatible version must use old-style definition. */
int average( va_alist )
va_dcl
{
int i, count, sum;
va_list marker;
va_start( marker ); /* Initialize variable arguments. */
for( sum = count = 0; (i = va_arg( marker, int)) != -1; count++ )
sum += i;
va_end( marker ); /* Reset variable arguments. */
return( sum ? (sum / count) : 0 );
}
#endif
其实这段代码就是说用stdarg.h头文件中的va_arg, va_end, va_start三个宏操作参数列表。既然是宏,自然可以完全不用。下面是我写的代码:
#include "stdafx.h"
void test(int x, ...)
{
void *argPtr=&x;
int y;
while((y=*(int *)(argPtr=((int *)argPtr)+1)) != -1)
printf("%d/n",y);
}
int main(int argc, char* argv[])
{
test(0,1,2,3,4,5,6,-1);
return 0;
}
达到同样的效果。其实很简单,参数传递是通过压栈操作实现的,第一个变量是栈顶元素,只要得到它的地址,通过简单的++就可以访问所有参数。但是有两个问题要注意:一是你不知道参数个数,换句话说你不知道参数栈的边界;二是你不知道参数的类型。你唯一知道的就是它们的地址。这个的负面影响也是不言而喻的。printf和scanf也是通过同样的方式实现的,也存在同样问题。看下面代码:
#include "stdio.h"
int main(int argc, char* argv[])
{
char formatData[32000];
for(int i=1;i<32000;i+=2)
{
formatData='%';
formatData='d';
}
printf(formatData);
return 0;
}
通过这个例子可以看出,这种变长参数的函数是很危险的,并不值得提倡.
变长参数函数
最新推荐文章于 2021-10-30 17:30:12 发布