I'm having trouble solving a problem in a function that receives variable parameters. I have a function that adds a variable number of numbers, its first parameter is the number of numbers to be added, and the others are the numbers themselves, it works when working with double numbers, but not when using numbers of type int, compiling this code output will be 60.00, as expected:
#include <stdio.h>
#include <stdarg.h>
double somaVariaveis(int qtd, ...)
{
va_list args;
int i;
double soma = 0;
va_start(args, qtd);
for(i = 0; i < qtd; i++)
soma += va_arg(args, double);
va_end(args);
return soma;
}
int main()
{
printf("soma de parametros variaveis: %.2lf", somaVariaveis(3, 10.0, 20.0, 30.0));
return 0;
}
Now, if I try to print the sum of integers:
printf("soma de parametros variaveis: %.2lf", somaVariaveis(3, 10, 20, 30));
The result will be 0.00;
Where did I go wrong? Should not cast occurred when I pass variables of type int and specific that I want double variables? I noticed a certain difficulty when working with variable parameters in relation to type, in another example, if I try to add float parameters:
#include <stdio.h>
#include <stdarg.h>
float somaVariaveis(int qtd, ...)
{
va_list args;
int i;
float soma = 0;
va_start(args, qtd);
for(i = 0; i < qtd; i++)
soma += va_arg(args, float);
va_end(args);
return soma;
}
int main()
{
printf("soma de parametros variaveis: %.2f", somaVariaveis(3, 10.0f, 20.0f, 30.0f));
return 0;
}
I get the following Warning, and I have a problem running.:
warning: 'float' is promoted to 'double' when passed through '...'
note: (so you should pass 'double' not 'float' to 'va_arg')
note: if this code is reached, the program will abort