Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable argument type in va_arg function in c

Tags:

c

I'm getting a warning by the gcc compiler and the program aborts if the following code is executed I couldn't get why? Would be great help if someone clarified it.

#include<stdio.h>
#include<stdarg.h>
int f(char c,...);
int main()
{
   char c=97,d=98;
   f(c,d);
   return 0;
}

int f(char c,...)
{
   va_list li;
   va_start(li,c);
   char d=va_arg(li,char); 
   printf("%c\n",d);
   va_end(li);
}

GCC tells me this:

warning: 'char’ is promoted to ‘int’ when passed through ‘...’ [enabled by default]
note: (so you should pass ‘int’ not ‘char’ to ‘va_arg’)
note: if this code is reached, the program will abort
like image 717
Vindhya G Avatar asked Jul 04 '12 22:07

Vindhya G


2 Answers

Arguments to variadic functions undergo default argument promotions; anything smaller than an int (such as char) is first converted to an int (and float is converted to double).

So va_arg(li,char) is never correct; use va_arg(li,int) instead.

like image 81
Oliver Charlesworth Avatar answered Sep 19 '22 10:09

Oliver Charlesworth


Yes, this appears to be a quirk in C standard. However, it looks like this is only to do with va_arg().

You can take a look at various implementations of printf() to see how to overcome this. For example, the one in klibc is pretty easy to read.

like image 45
errordeveloper Avatar answered Sep 18 '22 10:09

errordeveloper