Hacker News new | ask | show | jobs
by raible 45 days ago
I use something like this to turn __VA_ARGS__ into count/pointer:

  // Create a stack-allocated argv from N args gcc, clang, tcc, mingw, msvc, etc
  // argc is always correct, for portability argv has a dummy element when argc==0
  // This avoids problematic 0-length compound literal arrays.
  #define _ARG_CV(type, ...)  _ARG_CV1(((type []){0, __VA_ARGS__}))
  #define _ARG_CV1(array)     _ALEN(array) - 1, array + (_ALEN(array) > 1)
  #define _ALEN(array)         sizeof array / sizeof *array
Then it's just:

  #define sum(...) sum(_ARG_CV(int, __VA_ARGS__))
1 comments

Right, you can work around it with things like this, but it means you’re forcing the C compiler to parse a compound literal just to get its length, 5 times! when the preprocessor already knows the length of `__VA_ARGS__`. Such contortions when you want a little bit of info that the compiler already has are what cause your compiler times to blow up if you try to do anything sophisticated with the cpp.

Your version expands `sum(1, 2, 3, 4, 5, 6)` to:

    sum(sizeof ((int []){0, 1, 2, 3, 4, 5, 6}) / sizeof *((int []){0, 1, 2, 3, 4, 5, 6}) - 1, ((int []){0, 1, 2, 3, 4, 5, 6}) + (sizeof ((int []){0, 1, 2, 3, 4, 5, 6}) / sizeof *((int []){0, 1, 2, 3, 4, 5, 6}) > 1))
whereas with __VA_COUNT__ it is just:

    sum(6, (int[]){1, 2, 3, 4, 5, 6})