Is it possible to pass an anonymous array to the function when calling it, such as with a string? Why is Example 2 not working? How to make it work without using unnecessary variables?

example 1

void foo(char *arr) { cout << arr[2]; }; int main() { foo("123"); } 

example 2

 void foo(int *arr) { cout << arr[2]; }; int main() { foo({1,2,3}); } 

    1 answer 1

    Because the construction of the form {1, 2, 3} not, as you put it, an anonymous array. It is called braced-init-list and behaves differently, depending on the context. In your situation, you can do the following:

     void foo(std::initializer_list<int> arr) { cout << arr.size(); cout << arr[2]; }; 

    Where std::initializer_list is an object that behaves like a container and, in fact, contains a pair of pointers, so it does not heavily load run-time.