This section explains some of the background on why string literals are different than string variables. Being aware of this information is important. But we will not be intentionally programming with the C-strings that are described here - so there are many complexities to C-strings that are intentionally left out of this coverage.
Why? For historical reasons and compatibility with the C language. In C++, strings are objectsβbundles of data and functions that operate on that data. We will learn more about this in the coming sections. C does not have objects. So in C, strings are just an array (list) of characters. The original version of C++ used C style strings which are often referred to as βC stringsβ. Later, the <string> library and data type were added.
Thus it is important to keep in mind that there are multiple types of data that can store characters and the type of storage used changes what we can do with them. This is much like how we can store 2 into either an int x or a double x and the result of x / 3 will depend on its type. Here is a list of the types that we use when working with characters:
char.
Stores exactly one character. Stores the character as a numeric value.
Thus it makes sense to ask a string variable what itβs size is. But it does not make sense to ask that of a string literal. A string literal is not an object. It is βjustβ a sequence of characters.
cout << 'a' << endl; // a char literal
char c = 'a'; // a char variable
cout << "hello" << endl; // a string literal
string s = "hello"; // a string variable
As long as you keep those two facts in mind, and avoid trying to do work on string literals, you wonβt have to worry about other details. If you have a string literal to work with, store that literal into a variable and work with the variable.