Skip to main content

Section 9.4 strings vs C-strings

Note 9.4.1.

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.
A string literal like "Hello" does not have the string data type.
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.
  • string.
    Stores 0+ characters. Stores them as an object. The object contains a list of characters and functions to work with those characters.
  • string literal (C-string).
    A sequence of characters in quotes. Stored as a list of numeric values.
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.
Listing 9.4.1.
The two critical things to remember are:
  • ' indicates a char literal while " indicates a string literal
  • A literal value is different than a variable. In the case of a string, the variable and literal are very different.
Listing 9.4.2.
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.

Checkpoint 9.4.1.

You have attempted of activities on this page.