Why does int* ptr_arr_int = {1,2}; not work in C/C++?
"amruth"
is a const char[7]
type in C++, and a char[7]
type in C (although the behaviour on attempting to modify the string is undefined).
This can decay to a const char*
or char*
type respectively in some circumstances, such as yours.
Although an int[2]
will similarly decay to an int*
in some circumstances, {1, 2}
is neither an int[2]
nor a const int[2]
type; rather it is a brace-initialiser.
As said, the string is an const char[7]
array and while that can decay to a char*
, {1, 2}
cannot decay to int*
(it's an brace initializer list, similarly: std::initializer_list
). But note there is also the array []
declaration which allows you to automatically declare arrays. Combine that with the list-initialization since C++11 and you are able to initialize both via []
:
int ptr_arr_int[] = { 1,2 }; //OK
char ptr_arr_char[] = "amruth"; //OK
A string by itself already implies a storage class -- it's a static
(+effectively const
) char
array declared using special syntax.
In contrast to that, it's not clear how {1, 2}
in int *ptr_arr_int = {1, 2}
should be stored. Should it be static
or auto
?
If you want it auto
when in a local scope or static
when in file scope, then in C>=99 you can explicitly do int *ptr_arr_int = &(int[]){1,2}[0];
(the &[0]
is optional).
You could conceivably make this implicit, but how far would you take this?int ****x = {1,2};
initialized by creating an array, a pointer to it, a pointer to that etc., could result int quite a bit of code/data and hiding a lot of code/data under a simple construct isn't quite the C way. It would also not be clear when the brace syntax should be initializing the ultimate target basic type or some of the intermediate pointer(s).