Why is char* p = "..." right but int* p = {1,2} wrong?

arrays, c++

Solution

It is so because the language specification says so (independently for each respective language).

In both C and C++ string literal is a nameless object, an lvalue. Since it is an object, you can point to it with a pointer. At the same time `{1, 2, 3, 4}` is just a syntactic construct that does not represent an object. It is just a formal sequence of characters that form aggregate initializer syntax.

Meanwhile, in C language (since C99) there's a feature called compound literal, which allows one to form nameless objects of aggregate types. For example, the following initialization is valid

int *ival = (int []) {1, 2, 3, 4};

This is basically the "int array" counterpart of the first declaration. So, from C point of view, your second declaration is "wrong" simply because you used improper syntax.

Problem

``` const char *cval = "nothing"; // This is right. int *ival = {1, 2, 3, 4}; // This is wrong. ``` Why the first is right but the second is wrong ?

Original source