C++ Auto Keyword

why can’t we initialize an array with auto keyword in c++

Array is a collection of multiple values of same data types. It represents a range of memory. Array is not a pointer. It works like a pointer due to array to pointer decay.

The auto keyword identifies the type of value from the initializer.

int a = 1;                              // Compiler knows a and 1 both are of type int

int _array[] = {1, 2, 3};               // Compiler knows 1, 2 and 3 are of type int,
                                        // _array is of type int[] (a memory range of int)
                                        // rvalue is an std::initializer_list object
                                        // rvalue is converted implicitly to int[]

int* _pointer = new int[] {1, 2, 3};    // Compiler knows 1, 2 and 3 are of type int and
                                        // and that {1, 2, 3} is an std::initializer_list object
                                        // new int[] return the address to the memory range of 3 integers
                                        // which is accepted by _pointer which is of type int*

auto supposed_to_be_integer = 1;        // Compiler knows 1 is of type int
                                        // therefore, supposed_to_be_integer should be of type int

auto supposed_to_be_array[] = {1, 2, 3};
                                        // Compiler knows 1, 2 and 3 are of type int
                                        // and that {1, 2, 3} is an std::initializer_list object
                                        // supposed_to_be_array is of type auto[] (a memory range of auto)
                                        // incompatibility

auto supposed_to_be_pointer = new int[] {1, 2, 3};
                                        // Compiler knows 1, 2 and 3 are of type int and
                                        // new int[] return the address to the memory range of 3 integers
                                        // therefore, supposed_to_be_pointer should be of type int* and not int[]

Issue here is that any declaration of {} does not have a type. The compiler tries the implicit conversion to store the data. In case of auto, compiler cannot figure out what the object should be converted to.

It was supposed to work, but it does not. The issue is condemned by many and is supposed to be fixed. Look at this discussion.

More about std::initializer_list.
More about auto.

PS: Sorry for the late reply. I wanted to answer but it took 26 days. I was busy

1 Like