Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › C++ FUNDAMENTALS
The quote marks decide what kind of value you wrote. Double quotes make "code" a string literal containing four characters. Single quotes make 'c' a character literal containing exactly one char. The two forms are not interchangeable, even though both use quote marks.
"code"
'c'The complete text for the running example needs double quotes, so "code" can be used to initialize a string. Writing 'code' does not turn several letters into a string literal. It is not the single-character form, and it cannot initialize the string variable that holds the complete text.
Which literal can initialize word with the complete text code?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The declaration names the type, the variable, and its initial value in one line. std::string is the type for a sequence of characters, word is the variable name, and "code" is the initial value placed in that variable. The include makes the std::string type available.
#include <iostream>
#include <string>
int main() {
std::string word = "code";
std::cout << word << '\n';
}There is one variable here, not four separate variables. The value stored in word is the complete text code. The characters inside that text can be selected individually, but selecting one character does not split word into separate values.
Each character in word has a zero-based index. The first character c is at index 0, not index 1. Moving one position at a time gives o at index 1, d at index 2, and e at index 3. Each expression such as word[2] produces a char, while word itself remains the complete std::string value "code".
| EXPRESSION | INDEX | SELECTED CHAR |
|---|---|---|
| word[0] | 0 | c |
| word[1] | 1 | o |
| word[2] | 2 | d |
| word[3] | 3 | e |
std::string word = "code";
std::cout << word[0] << '\n';
std::cout << word[1] << '\n';
std::cout << word[2] << '\n';
std::cout << word[3] << '\n';Type the expression that selects d from word.
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
For this exact value, the only valid character indices are 0, 1, 2, and 3. Index 4 is beyond the final character e, so there is no stored character at that index. The fact that 4 comes immediately after 3 does not create another valid position.
std::string word = "code";
std::cout << word[3] << '\n'; // valid, selects e
std::cout << word[4] << '\n'; // out-of-bounds access