7

I need to create a string of 100 A characters.

Why does the following

std::string myString = {100, 'A'};

give different results than

std::string myString(100, 'A');

?

4
  • 1
    For universal initialization, simply replace '()' with '{}'. You should be doing std::string myString{100,'A'}; Commented Mar 13, 2013 at 16:25
  • 1
    @CrazyEddie but this is an example of where that change in brackets would radically change the behaviour of the program. The initializer_list constructor takes precedence over all others. The = sign makes no difference here. See demo. Commented Mar 13, 2013 at 16:37
  • 1
    @CrazyEddie How does that make a difference? The result is still not the same as std::string myString(100, 'A'); Commented Mar 13, 2013 at 16:38
  • @juanchopanza - ugh. OK. Thanks for the helpful correction. Commented Mar 13, 2013 at 20:47

2 Answers 2

14
std::string myString = {100, 'A'};

is initialization using initializer list. It creates a string with 2 characters: one with code 100 and 'A'

std::string myString(100, 'A');

calls the following constructor:

string (size_t n, char c);

which creates a string with 100 'A's

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

5 Comments

Formally, the first argument is merely a char with the value 100; it's ASCII if your system treats char values as ASCII. While that's quite common, it's not required by the C++ language definition, and there are systems where it's not true.
@Fanael - I don't know how hard it was, but it's an important point that is often overlooked, and merely editing the text doesn't remind people of it.
@PeteBecker: Does that mean that std::string s = { 100, 'A' }; is undefined behaviour? Wouldn't that invalidate most of the intention of creating the uniform initializer syntax in C++11?
@DanielFrey: it's not UB. CHAR_MAX is required to be at least 127, so 100 is a valid value of char regardless of what glyph it represents (if any -- not all values of char necessarily represent characters at all, so in theory you might have trouble printing it).
@DanielFrey - char is an arithmetic type as well as a character representation; there's nothing wrong with assigning 100 to a char object.
1

The first initializes it to values of 100 and A and the second calls a constructor overload of std::string.

1 Comment

Yes, that constructor would give you a string with 100 'A' characters.

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.