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

7
  • 2
    This looks like an XY problem. What are you trying to achieve with this? Commented Dec 20, 2018 at 16:06
  • 2
    This is trying to create a compound literal, but these only exist in C99 and above, not in C++. Commented Dec 20, 2018 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 Commented Dec 20, 2018 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. Commented Dec 20, 2018 at 16:10
  • 1
    If you want just get the length of VA_ARGS use this trick stackoverflow.com/a/2124385/10733631 Commented Dec 20, 2018 at 16:12

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.