I have written a small C program which involves variable arguments. See below:-
#include <stdio.h>
#include <stdarg.h>
double calculateAverage(int num,...)
{
va_list argumentList;
double sum=0;
int i;
va_start(argumentList,num);
for(i = 0; i < num; i++)
{
sum += va_arg(argumentList,double);
}
va_end(argumentList);
return(sum/num);
}
int main()
{
printf("%f\n",calculateAverage(3,1,2,3));
printf("%f\n",calculateAverage(4,2,4,6,8));
printf("%f\n",calculateAverage(4,2.0,4.0,6.0,8.0));
printf("%f\n",calculateAverage(3,1,2,3));
}
Output is:
0.000000
0.000000
5.000000
5.333333
Only calculateAverage(4,2.0,4.0,6.0,8.0) is giving expected output, i.e. when I specifically represent them with the decimal point.
Shouldn't
va_arg(argumentList,double)safely promote the numbers to double?How can
calculateAverage(3,1,2,3)give 2 results in 2 different places? Am I inside some 'undefined behavior' territory? If yes, how?
I am using gcc version 4.8.1.