boolean isArray = false;
There is no boolean
datatype in C++.
Also, the value of neither isArray
nor index
variable is ever used in the function.
typedef unsigned short WORD;
WORD current_item = va_arg(next_item, WORD);
This isn't going to work. Variadic arguments are promoted. unsigned short
promotes to int
(typically; on some exotic system, it might be unsigned int
). Using the non-promoted type with va_arg
will cause undefined behaviour. You could use a trick like this to get the correct type for any system:
using promoted_word = decltype(+WORD(0));
WORD current_item = WORD(va_arg(next_item, promoted_word));
WORD current_item = va_arg(next_item, WORD);
int current_item_size = sizeof(current_item) / sizeof(WORD);
The size of WORD
divided by the size of WORD
is always 1. There's no point in doing this.
I'm struggling with one of the two scenarios where current_item turns out to be an array instead of just an integer. How can I access the individual elements of this array and assign them to pOutList?
Function argument cannot be an array. But it can be a pointer to an element of an array, which I assume is what you mean. If that is the case, then you can get the pointer out of varargs like this:
WORD* current_item = va_arg(next_item, WORD*);
You can then copy the elements from array to array just like you would using any pointer to an element.
There's still two problems though: 1. There is no way of finding out the size of the array based on that pointer and 2. There is no way of finding out what type of arguments were passed (i.e. whether it was a( pointer to a)n array or an integer). You can take a look at the interface of printf
for an idea of how that problem may be solved. It is solved there using a format string where those types are specified. The length of the array is solved by using a sentinel value (the null terminator character). Another approach is to pass the length as a separate argument.
More generally though: I recommend that you not use C style varargs at all in C++. It's just too easy to shoot yourself in the foot. Variadic templates are much safer and more powerful way to achieve similar things.
That said, I don't quite understand what you're attempting to do, so I cannot confirm whether it makes sense to use any form of variadics.