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"
.
std::string
literals.
"foobar"s
, with the trailing s
,
but we won’t discuss it.
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.
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