Home > Enterprise >  How do you interpret this #define va_ arg(list,mode) ( (mode *) ( list = sizeof(mode) ) [-1]
How do you interpret this #define va_ arg(list,mode) ( (mode *) ( list = sizeof(mode) ) [-1]

Time:12-01

#define va_arg(list,mode) ( (mode *) ( list  = sizeof(mode) ) [-1]

I don't know [-1] how to see? Can the pointer point to this position?

i think this points to the previous value in mode

CodePudding user response:

#define va_arg(list,mode) ( (mode *) ( list = sizeof(mode) ) [-1]

That is an implementation of the va_arg macro to be defined by <stdarg.h> for C’s variable arguments features in C 2018 7.16.

When this macro is used, list should be a va_list object, and mode should be a type. In this C implementation, va_list is apparently implemented as a pointer to a character type or as a pointer to void in a C implementation that extends pointer arithmetic to work with void *.

Then list = sizeof(mode) advances list by the number of bytes in an object of type mode, to account for the argument that is about to be “consumed” by the macro. Then the (mode *) cast preceding ( list = sizeof(mode) ) converts the pointer to point to the desired type. However, due to the =, it is now pointing after the desired argument, and that pointer value is the result of the = expression and the cast. So the [-1] after it is used to fetch the element just prior to where list is pointing.

I suspect this slightly awkward construction with [-1] was used to avoid using list twice in the macro, which is good practice to avoid evaluating side effects more than once, in case the macro argument is an expression with side effects.

Note that using list in list = sizeof(mode) is probably an error or oversight; it should be (list) = sizeof(mode).

  • Related