42
, 1.2e-24
, 'x'
, "foo"
, true
, or nullptr
.
const
variables are not literals. They’re variables that don’t vary.
char
: 'X'
.
"alpha beta gamma"
.
const char []
, or const char *
.
std::string
literals.
"foobar"s
, with the trailing s
.
const std::string
.
A "string literal"
is an anonymous array of constant characters.
These are equivalent:
cout << "FN-2187";
FN-2187
const char whatever[] = "FN-2187"; cout << whatever;
FN-2187
const char whatever[] = "FN-2187"; const char *p = &whatever[0]; cout << p;
FN-2187
"string literal"
is like an anonymous array.
Sequence | Meaning | Sequence | Meaning |
---|---|---|---|
\a | bell | \' | ' |
\b | backspace | \" | " |
\f | form feed | \\ | \ |
\n | newline | \0 ddd | 0–3 octal digits |
\r | carriage return | \x dd | 1–∞ hex digits |
\t | horizontal tab | \u dddd | Unicode U+dddd |
\v | vertical tab | \U dddddddd | Unicode U+dddddddd |
Two adjacent string literals are merged into one at compile-time:
cout << "alpha beta " "gamma delta " "epsilon\n";
alpha beta gamma delta epsilon
cout << "Business plan:\n\n" "1. Collect underpants\n" "2. ?\n" "3. Profit\n";
Business plan: 1. Collect underpants 2. ? 3. Profit
A raw string starts with R"(
and ends with )"
.
The parens are not part of the string.
cout << R"(Don't be "afraid" of letters: \a\b\c\d\e\f\g)";
Don't be "afraid" of letters: \a\b\c\d\e\f\g
Cool! Quotes inside of quotes!
What if the string contains a right paren? I want to emit:
A goatee! :-)" Cool!
cout << "A goatee! :-)" Cool!";
c.cc:1: warning: missing terminating " character c.cc:1: error: missing terminating " character
That didn’t work. The )"
at the bottom of the face
was taken to be the end of the raw string.
A raw string starts with:
R"
whatever-you-like-up-to-sixteen-chars(
and ends with:
)
the-same-up-to-sixteen-chars"
cout << R"X(A goatee! :-)" Cool!)X";
A goatee! :-)" Cool!
cout << R"WashYourHair(What the #"%'&*)?)WashYourHair";
What the #"%'&*)?
cout << R"(The degenerate case)";
The degenerate case
if ("foo" < "bar") cout << "😢";
c.cc:1: warning: comparison with string literal results in unspecified behavior 😢
"marx"
and "marx"
two arrays or one? Who knows‽
g++ -Wall
will detect this deplorable code.
strcmp(a,b)
returns:
a
<b
.
a
==b
.
a
>b
.
std::string
sstd::string
values, or to compare a std::string
with a C-style string, use the usual operators:
< > <= >= == !=
std::string::compare()
,
which has the same three-way return value as strcmp.
string name = "Conan O’Brien"; if (name == "Conan O’Brien") cout << "good 1\n"; if (name < "Zulu") cout << "good 2\n"; if (name > "Andy Richter") cout << "good 3\n"; if (name == name) cout << "good 4\n";
good 1 good 2 good 3 good 4