3

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?

1
  • Why you asking only about char pointers? Commented Sep 2, 2018 at 10:59

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting - are string literals the only type that can behave this way?
@tomysshadow As far as I know, yes. String literals are a bit special in the language.
1

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};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.