Cautions for C length-alterable parameters

C / C ++  use va_list,va_start,va_arg and va_end(all defined  in  header file < stdarg.h > ) to process with functions that have length - alterable parameters like  this :
void  Foo( int  a,...);

the defination of va_macro:
typedef 
char *  va_list;               
#define  va_start(ap,p) (ap=(char*)(&(p)+1)) 
#define  va_arg(ap,type)((type*)(ap+=sizeof(type)))[-1] 
#define  va_end(ap) 
    or
typedef 
char *  va_list; 
#define  _intsizeof(n)  ((sizeof(n)+sizeof(int)-1)&~(sizeof(int)-1)) 
#define  va_start(ap,v) (ap =(va_list)&v+_intsizeof(v)) 
#define  va_arg(ap,t)   (*(t*)((ap+=_intsizeof(t))-_intsizeof(t))) 
#define  va_end(ap)     (ap=(va_list)0)

in  function like  this :
template
< typename T >
void  Foo( int  n,...)
{
    
const int total=n;
    va_list args;
    va_start(args,n);

    
for(;n>0;--n)
        num[total
-n]=va_arg(args,T);//external defination for num[]
    va_end(args);
}


if  we use it like  this :
void  TestFoo1()
{
    Foo
<double>(5,1,2,3,4,5);
}

it would never 
get  the correct answer because the arguments that pushed into the stack from the 2rd to 5th parameters namely numbers  1  to  5  would be processed like  int ,not  double .At the time the arguments that been pushed into stack,the function wont ' t know that it would be process like double.

We can 
do  the call explicitly like  this :
Foo
< double > ( 2 , double ( 1 ), double ( 2 ));
or
double  a = 1 ,b = 2 ;
Foo
< double > ( 2 ,a,b);

Let
' s go ahead for another function;
void  TestFoo2()
{
    Foo
<float>(2,float(1),float(2));
}


it won
' t work as the float number will be updated into double even if you declared it explicitly.Be careful!
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值