0

I want to get the length of VA_ARGS

I used the answer of this question https://stackoverflow.com/a/2124433/7388699 but if doesn't work!

#define PIN_ARRAY_LENGTH(...) ((size_t)(sizeof((int[]){__VA_ARGS__})/sizeof(int)))

size_t c = PIN_ARRAY_LENGTH(1, 5, 7, 9);

I also tried

size_t x = sizeof((int[]){ 1, 6, 8 }) / sizeof(int);

It does not compile, I get the error: cast to incomplete array type "int []" is not allowed

Tobi G
  • 28
  • 1
  • 8
  • 2
    This looks like an XY problem. What are you trying to achieve with this? – NathanOliver Dec 20 '18 at 16:06
  • 2
    This is trying to create a compound literal, but these only exist in C99 and above, not in C++. – Quentin Dec 20 '18 at 16:07
  • I want to pass CREATE_PIN_ARRAY(1, 6, 8) end then let it expand to new const unsigned int[]{1, 6, 8}, 3 I have problems to pass the size of the array – Tobi G Dec 20 '18 at 16:09
  • `#define CREATE_PIN_ARRAY(...) const unsigned int something[] { __VA_ARGS__ }`? Not sure what you're gaining by hiding that behind a macro though. Edit: oh, there's the array size in there too. Hold on. – Quentin Dec 20 '18 at 16:10
  • Because I don't wat to pass the size manually, I want it to automatically append the size – Tobi G Dec 20 '18 at 16:11
  • 1
    If you want just get the length of VA_ARGS use this trick https://stackoverflow.com/a/2124385/10733631 – Dmytro Dadyka Dec 20 '18 at 16:12
  • I tried it but it does not work it is just empty – Tobi G Dec 20 '18 at 16:14

2 Answers2

1

Compound literals are out of the question, but you can create the array rvalue you need through a typedef:

using int_c_array = int[];

#define count_args(...) \
    (sizeof(int_c_array {__VA_ARGS__}) / sizeof(int))
Quentin
  • 62,093
  • 7
  • 131
  • 191
1

Variation of Quentin's answer:

#define NUM(...) (std::tuple_size<decltype(std::make_tuple(__VA_ARGS__))>::value)

This does not require an alias and works with arbitrary types:

size_t n = NUM(7, 10.12, "hello world");
Aconcagua
  • 24,880
  • 4
  • 34
  • 59