同样的可变参数函数, 为什么对float类型就不行呢?

lightnut 2009-02-20 01:22:16
某哥们的原贴.
http://topic.csdn.net/u/20090220/11/951b405d-802c-4266-a0e4-da4f2b0991e9.html
我试图去解决上贴的问题, 失败了:(.

我用模板重写了上贴的可变参数函数, 发现对int, double类型没有问题, 惟独float的结果错误.
不只为何? (编译环境:VC2005)


#include <iostream>
#include <cstdarg>

template <class T>
T sum(int n,T b,...)
{
va_list ap;
T temp;
va_start(ap, b);
T sum1=b;
for(int i=0;i<n-1;i++)
{
temp=va_arg(ap,T);
sum1 += temp;
}
va_end(ap);
return(sum1);
}

int main()
{
int intA = 2;
int intB = 3;
std::cout <<intA<<"+"<<intB<<"="<<sum(2, intA, intB)<<'\n';

double doubleA = 2.2;
double doubleB = 3.3;
std::cout <<doubleA<<"+"<<doubleB<<"="<<sum(2, doubleA, doubleB)<<'\n';

// 下面输出的结果是错误的!! why?
float floatA = 2.1f;
float floatB = 3.1f;
std::cout <<floatA<<"+"<<floatB<<"="<<sum(2, floatA, floatB)<<'\n';

return 0;
}
...全文
146 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
lightnut 2009-02-20
  • 打赏
  • 举报
回复
自己找到答案:

http://c-faq-chn.sourceforge.net/ccfaq/node266.html

``参数默认晋级" 规则适用于在可变参数中的可变动部分: 参数类型为 float 的总是晋级 (扩展) 到 double, char 和 short int 晋级到 int。所以 va_arg(arpg, float) 是错误的用法。应该总是用 va_arg(arpg, double)。 同理, 要用 va_arg(argp, int) 来取得原来类型是 char, short 或 int 的参数。基于相同理由, 传给 va_start() 的最后一个 ``固定" 参数项的类型不会被晋级。
lightnut 2009-02-20
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 fox000002 的回复:]
看看 g++ 的提示



C/C++ codetest.cpp: In function ‘T sum(int, T, ...) [with T = float]’:
test.cpp:33: instantiated from here
test.cpp:13: warning: ‘float’ is promoted to ‘double’ when passed through ‘...’
test.cpp:13: warning: (so you should pass ‘double’ not ‘float’ to ‘va_arg’)
test.cpp:13: note: if this code is reached, the program will abort
[/Quote]

原来是这样!? 我将Warning开到最高, VC也不给提示.
fox000002 2009-02-20
  • 打赏
  • 举报
回复
看看 g++ 的提示


test.cpp: In function ‘T sum(int, T, ...) [with T = float]’:
test.cpp:33: instantiated from here
test.cpp:13: warning: ‘float’ is promoted to ‘double’ when passed through ‘...’
test.cpp:13: warning: (so you should pass ‘double’ not ‘float’ to ‘va_arg’)
test.cpp:13: note: if this code is reached, the program will abort
lightnut 2009-02-20
  • 打赏
  • 举报
回复
怎么忘记加分了? 200慢慢加........

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧