I wrote below C program to call function with variable number of arguments.
#include<stdio.h>
#include<stdarg.h>
void display(int, int, ...);
int main()
{
display(1,5,1,2,3,4,5);
display(2,3,'A','B','C');
printf("\n");
return 0;
}
void display(int type, int tot_num, ...)
{
int i, j;
char c;
va_list ptr;
va_start (ptr, tot_num);
switch(type)
{
case 1:
for (j=0; j<tot_num; j++)
{
i = va_arg (ptr, int);
printf("%d ",i);
}
break;
case 2:
for (j=0; j<tot_num; j++)
{
c = va_arg(ptr, char);
printf("%c ",c);
}
}
}
However when I compile the program i get below warning from gcc.
-bash-4.1$ gcc varArg3.c
varArg3.c: In function âdisplayâ:
varArg3.c:41: warning: âcharâ is promoted to âintâ when passed through â...â
varArg3.c:41: note: (so you should pass âintâ not âcharâ to âva_argâ)
varArg3.c:41: note: if this code is reached, the program will abort
-bash-4.1$
Line 41 is c = va_arg(ptr, char);
When I read the man 3 page for va_arg it was mentioned as below:
If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.
When I read this, I was thinking that c = va_arg(ptr, char);
is correct because, the data in the variable argument list were characters . However above warning by gcc suggest that variable arguments passed are not really characters but integers.
As suggested by gcc, I change it to c = va_arg(ptr, int);
, and now I get no warnings. Also I get expected output when I run the program.
So, were the characters (in second call to diplay()
in main()
) passed as integers to display()
?
Thanks.