As Chapter 3, “Dealing with Data,” mentioned, C++11 makes the brace form of initialization (list-initialization) a universal form for all types. Arrays already use list-initialization, but the C++11 version adds a few more features.
First, you can drop the =
sign when initializing an array:
double earnings[4] {1.2e4, 1.6e4, 1.1e4, 1.7e4}; // okay with C++11
Second, you can use empty braces to set all the elements to 0:
unsigned int counts[10] = {}; // all elements set to 0
float balances[100] {}; // all elements set to 0
Third, as discussed in Chapter 3, list-initialization protects against narrowing:
long plifs[] = {25, 92, 3.0}; // not allowed
char slifs[4] {'h', 'i', 1122011, ' '}; // not allowed
char tlifs[4] {'h', 'i', 112, ' '}; // allowed
The first initialization fails because converting from a floating-point type to an integer type is narrowing, even if the floating-point value has only zeros after the decimal point. The second initialization fails because 1122011
is outside the range of a char
, assuming we have an 8-bit char
. The third succeeds because, even though 112
is an int
value, it still is in the range of a char
.
The C++ Standard Template Library (STL) provides an alternative to arrays called the vector
template class, and C++11 adds an array
template class. These alternatives are more sophisticated and flexible than the built-in array composite type. This chapter will discuss them briefly later, and Chapter 16, “The string
Class and the Standard Template Library,” discusses them more fully.
A string is a series of characters stored in consecutive bytes of memory. C++ has two ways of dealing with strings. The first, taken from C and often called a C-style string, is the first one this chapter examines. Later, this chapter discusses an alternative method based on a string
class library.
The idea of a series of characters stored in consecutive bytes implies that you can store a string in an array of char
, with each character kept in its own array element. Strings provide a convenient way to store text information, such as messages to the user (“Please tell me your secret Swiss bank account number”) or responses from the user (“You must be joking”). C-style strings have a special feature: The last character of every string is the null character. This character, written