0

I want to write a macros to print pairs of {variable name, variable value}. The variables are supposed to be arguments of variadic macros. I made a simple code, that produces compilation error: "expected expression" in cases when number of variables to print is less than maximum possible number.

#define IS_EMPTY(...) ( sizeof( (char[]){#__VA_ARGS__} ) == 1 )
#define PRINT_VAR(x) std::cout << "\"" << #x << "\": " << (x) << " ";

#define PRINT_VARS3(x, ...) {PRINT_VAR(x); }

#define PRINT_VARS2(x, ...) {PRINT_VAR(x); \
                             if constexpr (not IS_EMPTY(__VA_ARGS__)) PRINT_VARS3(__VA_ARGS__); }
#define PRINT_VARS1(x, ...) {PRINT_VAR(x); \
                             if constexpr (not IS_EMPTY(__VA_ARGS__)) PRINT_VARS2(__VA_ARGS__); }
#define PRINT_VARS(x, ...)  {PRINT_VAR(x); \
                             if constexpr (not IS_EMPTY(__VA_ARGS__)) {\
                             PRINT_VARS1(__VA_ARGS__); \
                             } \
                             std::cout << "\n";}


int i = 100;
float j = 200.5;
int k = 300;
float l = -0.576f;

PRINT_VARS(i, j, k, l); // works fine 
//PRINT_VARS(i, j); // compilation error


Thing that I cant understand, if I remove << (x) from second line, PRINT_VARS work with different number of arguments. What is the reason and how to fix it? Thank you!

Removing << (x) from the second line makes code compliable and working except it cant printout the variables values.

I expect the compiler not to check if constexpr branches at 0 condition. But it looks like empty VA_ARGS passed to PRINT_VAR macros that leads to this error.

I have tried this code with gcc12 and clang14 compilers.

Karim
  • 1
  • 1
    The stuff compiled out by `if constexpr` must still be lexically well-formed. You basically end up with `std::cout << ();` - that's invalid even under `if constexpr(false)` – Igor Tandetnik Dec 11 '22 at 02:01

0 Answers0