在va_arg(双)返回每次无效值 [英] va_arg( , double) return each time an invalid value
问题描述
当我使用的va_arg(AP,双)运行此示例程序,我发现在va_arg返回无效数据,为0,而不是3或1.2,而不是1,这样,如果我通过整数值没有.00,而不是双格式它得到一个垃圾数据(IE的3而不是3.00)!
的#include<&stdio.h中GT;
#包括LT&;&STDARG.H GT;
无效FUNC(int类型){
的printf(%S:%d个\\ n,__ __ FUNC,S);
}无效VAR(诠释计数,...){
va_list的AP;
的va_start(AP,计数);
双A =在va_arg(AP,双面);
的printf(%F \\ N,一);
va_end用来(AP);}无效的主要(无效){
的printf(%s和%D,%S \\ n,__ __ FILE __ __ LINE __ DATE__);
FUNC(__ LINE__);
VAR(1,3);
VAR(1,1.2);
VAR(1,1);}
输出是:
try.c,24,2012年9月25日
FUNC:25
0.000000
1.200000
1.200000
可变参数的函数(即,它采用可变数目由省略号(显示参数的函数 ...
)参数)有printf的某些特殊功能的情况下>和 scanf函数
,编译器没有努力,以验证您传递正确类型的参数给他们。
在你的情况下,函数期待一个双击
参数,但你想在 INT
。编译器不会做任何推广,从这里 INT
到双击
,所以不确定的行为。你需要始终在双击
值传递在这里,无论是作为一个明确的双击
恒定值,如 1.0
,或使用强制类型转换进行转换。
When I run this sample program using va_arg(ap,double), I found va_arg return invalid data, as 0 instead of 3 or 1.2 instead of 1, such that if I pass integer value without .00 instead of double format it get a garbage data (ie 3 instead of 3.00)!!!
#include <stdio.h>
#include <stdarg.h>
void func(int s){
printf("%s: %d\n",__func__,s);
}
void var(int count,...){
va_list ap;
va_start(ap,count);
double a = va_arg(ap,double);
printf("%f\n",a);
va_end(ap);
}
void main(void ) {
printf("%s,%d,%s\n",__FILE__,__LINE__,__DATE__);
func(__LINE__);
var(1,3);
var(1,1.2);
var(1,1);
}
The Output is:
try.c,24,Sep 25 2012
func: 25
0.000000
1.200000
1.200000
Variadic functions (that is, functions which take a variable number of arguments indicated by the ellipsis (...
) parameter) have weak typing in C. Except in the case of certain special functions like printf
and scanf
, the compiler makes no effort to verify that you're passing the correct types of arguments to them.
In your case, the function is expecting a double
parameter, but you're trying to pass in an int
. The compiler does not do any promotion here from int
to double
, so undefined behavior results. You need to always pass in a double
value here, either as an explicit double
constant value such as 1.0
, or perform the conversion using a typecast.
这篇关于在va_arg(双)返回每次无效值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!