Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard C cast of va_arg return value warning

I am developing a C program and have been stumped by this warning. I want to retrieve arguments from the list using va_arg.

args[i] = (int) va_arg(argptr, int); 

or

args[i] = (char) va_arg(argptr, char);

the problem that am getting this warning:

... void *' differs in levels of indirection from 'int'...

the same also for char case. Any explanation for that?

code:

void test_function(va_list argptr, int (*callback)(),
                   int ret_typel)
{
  int i ;
  int arg_typel;
  int no_moreb = TRUE;
  void *args[MAX_FUNCTION_ARGS];
  for (i=0; no_moreb; i++) {
    arg_typel = (int)va_arg(argptr, int);
    switch(arg_typel) {
    case F_INT:
      args[i] = (int) va_arg(argptr, int);
      break;
    case F_CHAR:
      args[i] = (char) va_arg(argptr, char);
      break;
    default:
      no_moreb = FALSE;
      i--;
      break;
    }
  }
}
like image 545
Aymanadou Avatar asked Nov 25 '25 11:11

Aymanadou


1 Answers

A point of detail about the use of va_arg().

You cannot use:

va_arg(argptr, char);

without invoking undefined behaviour (which is bad!). The variable arguments to a varargs function undergo promotions: float is passed as double, and char, unsigned char, signed char, short, unsigned short undergo promotion to int or unsigned (int) as required. Therefore, you can never pull a char directly with va_arg; you can only specify promoted types. You would have to write:

char c = (char) va_arg(argptr, int);
float f = (float) va_arg(argptr, double);

This time, the cast occurs as a result of the assignment; saying it happens with the cast is not strictly necessary, but does no harm (though I probably wouldn't write the cast in my own code).

like image 164
Jonathan Leffler Avatar answered Nov 28 '25 01:11

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!