返回   cpper编程论坛 > 技术杂烩
注册账号 论坛帮助 会员列表 日历事件 搜索 今日新帖 标记版面已读

技术杂烩 找不到地方的技术问题?这里!

回复
 
LinkBack 主题工具 显示模式
  #1 (permalink)  
旧 2005-06-25
bankrock 的头像
高级会员
 
注册日期: 2003-12-11
帖子: 847
文章: 7
bankrock 正向着好的方向发展
默认 float类型在不定参数函数中的提取

以下程序是在VC6中运行的:
代码:
#include <stdarg.h> #include <stdio.h> void pag(int a, ...) { va_list ap; double x1; float x2; va_start(ap, a); x1 = va_arg(ap, double); x2 = va_arg(ap, float); printf("Arg1 is %f, Arg2 is %f", x1, x2); va_end(ap); } void main(void) { double a = 10.2313; float b = 2.47f; pag(3, a, b); }
b这个float类型的参数在用va_arg提取的时候显示不正确,把b改为其他类型就没问题,va_arg为什么不能正确处理float类型呢?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #2 (permalink)  
旧 2005-06-26
cat cat 当前离线
高级会员
 
注册日期: 2003-11-06
帖子: 1,563
文章: 6
cat 正向着好的方向发展
默认

太小了吧~ 4字节起版, 所谓加宽.

google搜来的:
引用:
va_arg (argp, float);

  这样做可以吗?

  答案与分析:

  不可以。在可变长参数中,应用的是"加宽"原则。也就是float类型被扩展成double;char, short被扩展成int。因此,如果你要去可变长参数列表中原来为float类型的参数,需要用va_arg(argp, double)。对char和short类型的则用va_arg(argp, int)。
http://blog.csdn.net/canvashat/archi...16/218429.aspx
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #3 (permalink)  
旧 2005-06-26
bankrock 的头像
高级会员
 
注册日期: 2003-12-11
帖子: 847
文章: 7
bankrock 正向着好的方向发展
默认

在stdarg.h里找实现,发现有很多版本,估计是用在不同的平台上的。其中有这么一段注释:
引用:
Because of parameter passing conventions in C:
use mode=int for char, and short types
use mode=double for float types
use a pointer for array types
于是做了一下测试,发现对于不定参数来说确实如此,但是对于确定参数却有些许不同:
代码:
#include <stdarg.h> #include <stdio.h> #include <stdlib.h> void pag(char a, ...) //这里符合上面的注释 { printf("arg2 is %f, arg3 is %f", *( (double*)((int*)(&a) + 1) ), *( (double*)((int*)(&a) + 1) + 1 ) ); } void pag1(char a, float b, double c)//这里char要扩充,但float还是float { printf("arg2 is %f, arg3 is %f", *( (float*)((int*)(&a) + 1) ), *( (double*)( (float*)((int*)(&a) + 1) + 1 ) ) ); } void main(void) { float a = 2.47f; double b = 10.2313; pag(3, a, b); pag1(3, a, b); system("pause"); }
可能是VC6自己的名堂,反正知道了不定参数如此就可以了,嘿嘿
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
回复

书签

主题工具
显示模式

发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛启用 表情符号
论坛启用 [IMG] 代码
论坛禁用 HTML 代码
Trackbacks are 启用
Pingbacks are 启用
Refbacks are 启用



所有时间均为格林尼治时间 +9。现在的时间是 08:40 AM


Powered by vBulletin® 版本 3.7.0
版权所有 ©2000 - 2009,Jelsoft Enterprises Ltd.
(C) Copy Right All Right Reserved 2001 - 2007

Search Engine Friendly URLs by vBSEO 3.1.0