va_arg( , double) 每次返回一个无效值 [英] va_arg( , double) return each time an invalid value

查看:22
本文介绍了va_arg( , double) 每次返回一个无效值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 va_arg(ap,double) 运行这个示例程序时,我发现 va_arg 返回无效数据,作为 0 而不是 3 或 1.2 而不是 1,这样如果我传递没有 .00 而不是双格式的整数值得到一个垃圾数据(即 3 而不是 3.00)!!!

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);

}

输出是:

try.c,24,Sep 25 2012
func: 25
0.000000
1.200000
1.200000

推荐答案

可变参数函数(即采用省略号 (...) 参数指示的可变数量参数的函数)具有C 中的弱类型.除了像 printfscanf 这样的特殊函数,编译器不会去验证你传递的参数类型是否正确

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.

在您的情况下,该函数需要一个 double 参数,但您试图传入一个 int.编译器在这里没有做任何从 intdouble 的提升,所以会导致未定义的行为.您需要始终在此处传入 double 值,作为显式 double 常量值(例如 1.0),或使用类型转换执行转换.

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( , double) 每次返回一个无效值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆