0

I want the MSK_LOGD(1) to get converted to PRINT_0 but It is getting converted to PRINT_COUNT_ARGS(1)(1)

Can you suggest the changes to get the required output

#define PRINT_0 printf("zero");

#define COUNT_ARGS(...) COUNT_ARGS_UPTO_3(__VA_ARGS__, 3, 2, 1, 0)

#define COUNT_ARGS_UPTO_3(a, b, c, d, count, ...) count

#define PRINT(n, ...) PRINT_##n(__VA_ARGS__)

#define MSK_LOGD(...) PRINT(COUNT_ARGS(__VA_ARGS__), __VA_ARGS__)

int main(void)
{
  
  MSK_LOGD(1)
  return (0);
}
Majid Hajibaba
  • 3,105
  • 6
  • 23
  • 55
SRIKANTH
  • 65
  • 7
  • Why doesn't it work? What did you expect and what did you get instead? What kind of arguments and types must the macro be able to handle? – Lundin Dec 23 '21 at 12:53
  • arguments are of integer types – SRIKANTH Dec 23 '21 at 12:59
  • 4
    You have one dummy argument too much, needs to be `COUNT_3(a, b, c, count, ...) count` – more important: `PRINT_##n` needs an additional level of indirection (compare string concatenation problem), so `#define PRINT(n, ...) PRINT_N(n, __VA_ARGS__); #define PRINT_N(n, ...) PRINT_##n(__VA_ARGS__)`. Be aware, though, that `MSK_LOGD()` would still count one argument, as there's one *empty* token. And I recommend *not* adding the semicolons to your `PRINT_X` macros – this way one is required to add it to every call to `MSK_LOGD`, so it looks more like a function. – Aconcagua Dec 23 '21 at 13:17

1 Answers1

0

See this answer on How to pass a macro's result to another macro?

So you should use #define CONC(a,b) a ## b and your solution is as:


#define CONC(a,b) a ## b

#define PRINT_0 printf("zero");

#define COUNT_ARGS_UPTO_3(a, b, c, d, count, ...) count

#define COUNT_ARGS(...) COUNT_ARGS_UPTO_3(__VA_ARGS__, 3, 2, 1, 0)

#define PRINT(n, ...) CONC(PRINT_,n)(__VA_ARGS__)

#define MSK_LOGD(...) PRINT(COUNT_ARGS(__VA_ARGS__),__VA_ARGS__)

int main(void)
{
  
  MSK_LOGD(1);
  return (0);
}
Majid Hajibaba
  • 3,105
  • 6
  • 23
  • 55