Simple question. I am aware I should just be using std::string, but am curious why this works:
const char* example = "test";
while this results in "too many initializer values" on the second character?
const char* example = {0x74, 0x65, 0x73, 0x74, 0x00};
Shouldn't these two things be exactly equivalent?
The difference is that string literals are arrays all of their own. "test" is used here not as an initializer of an array (a special case where it would be equivalent to { 't', 'e', 's', 't', '\0' }), but the same way as any other value would be.
In other words, when you use a string literal "test" in your code, the compiler automatically creates something like
static const char __str_literal0[] = {'t', 'e', 's', 't', '\0'};
and then
const char *example = "test";
is compiled as if it were
const char *example = __str_literal0;
i.e. it simply points to the (already existing, static) char array.
On the other hand, if you try to use an initializer list, the compiler will set the first field of your variable (that's just example itself) to the first value in the initializer list (example = 0x74), and then complain that you have too many initializers in your list.
Shouldn't these two things be exactly equivalent?
In your second example you are trying to initialize a pointer using copy-list initialization, which is quite far in terms of equivalency from your first example.
Otherwise (if T is not a class type), if the braced-init-list has only one element and either T isn't a reference type or is a reference type that is compatible with the type of the element, T is direct-initialized (in direct-list-initialization) or copy-initialized (in copy-list-initialization), except that narrowing conversions are not allowed.
Even if you supply only one element:
const char* example = {0x74};
to stop compiler complaining about the number of arguments, it is still an error because for a valid copy-initialization you need to supply a pointer and not an int.
char a = 'c';
const char* example = {&a};
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