Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } 
like image 616
Jeremy Friesner Avatar asked Jul 16 '09 22:07

Jeremy Friesner


People also ask

What is the meaning of anonymous array in C?

Answer: Anonymous class is a class which has no name given to it. C++ supports this feature. These classes cannot have a constructor but can have a destructor. These classes can neither be passed as arguments to functions nor can be used as return values from functions.

When array is passed as an argument it indicates the?

1) In C, if we pass an array as an argument to a function, what actually get passed? The correct option is (b). Explanation: In C language when we pass an array as a function argument, then the Base address of the array will be passed.

What is an anonymous array also give an example?

An array in Java without any name is known as an anonymous array. It is an array just for creating and using instantly. Using an anonymous array, we can pass an array with user values without the referenced variable.

When passing an array to a function How must the array argument be written how is the corresponding formal argument written?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.


2 Answers

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}; } 
like image 71
rlbond Avatar answered Oct 09 '22 11:10

rlbond


It's allowed with a typecast in C++11 and in extern "C" with C99:

void PrintArray(size_t len, const int *array) {     for(size_t i = 0; i < len; i++)         printf("%d\n", array[i]); }  int main(int argc, char **argv) {     PrintArray(5, (const int[]){1, 2, 3, 4, 5});     return 0; } 
like image 21
Adam Rosenfield Avatar answered Oct 09 '22 10:10

Adam Rosenfield