Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad style or incorrect to access va_arg macro by reference?

I got a line of code where this is pretty useful:

void *test;
/*...*/
test = &va_arg(arg_list, int);

I was just trying this, as i thought, this is a macro and not a function, so it might work. I didn't really was expecting it to work, but it does exactly what I want.

But now I'm not sure about the lifetime of the address and other risks which may occur of this style.

Could anyone tell me why using the reference of the va_arg 's value this way is safe / unsafe?

like image 656
dhein Avatar asked Oct 20 '22 06:10

dhein


1 Answers

C99 standard, section 7.15.1.1 (emphasis mine):

The va_arg macro expands to an expression that has the specified type and the value of the next argument in the call.

This implies that va_arg does not necessarily evaluate to an lvalue; taking the address of whatever it expands to is unsafe: an lvalue can be used as an expression, but not every expression is an lvalue. Consider the expression 3+4. It doesn't make sense to take the address of that.

So, no, you shouldn't do it.

UPDATE: As pointed out in the comments, taking the address of an expression that is not an lvalue will cause a compilation error. So, if the code compiles, then it should be safe. The unportability issues arise from the fact that it may not compile in other platforms where va_arg() expands to something that is not an lvalue.

like image 95
Filipe Gonçalves Avatar answered Oct 23 '22 07:10

Filipe Gonçalves