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 likeprintfandscanf, 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
doubleparameter, but you’re trying to pass in anint. The compiler does not do any promotion here frominttodouble, so undefined behavior results. You need to always pass in adoublevalue here, either as an explicitdoubleconstant value such as1.0, or perform the conversion using a typecast.