Jeremy Friesner Jeremy Friesner - 1 month ago 6
C++ Question

Is there any way to pass an anonymous array as an argument in C++?

I'd like to be able to declare an array as a function argument in C++, as shown in the example code below (which doesn't compile). Is there any way to do this (other than declaring the array separately beforehand)?

#include <stdio.h>

static void PrintArray(int arrayLen, const int * array)
{
for (int i=0; i<arrayLen; i++) printf("%i -> %i\n", i, array[i]);
}

int main(int, char **)
{
PrintArray(5, {5,6,7,8,9} ); // doesn't compile
return 0;
}

Answer

If you're using older C++ variants (pre-C++0x), then this is not allowed. The "anonymous array" you refer to is actually an initializer list. Now that C++11 is out, this can be done with the built-in initializer_list type. You theoretically can also use it as a C-style initializer list by using extern C, if your compiler parses them as C99 or later.

For example:

int main()
{
    const int* p;
    p = (const int[]){1, 2, 3};
}