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: 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.
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.
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.
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.
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}; }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With