CS253 String Literals
Literals are constants, like
42
, 1.2e-24
, 'x'
, "foo"
, true
, or nullptr
.
This is a char
: 'X'
.
This is a C-style string literal: "alpha beta gamma"
.
(single quotes for a single character)
C++ 2011 has no std::string
literals.
C++ 2014 has "foobar"s
, with the trailing s
,
but we won’t discuss those.
A "string literal"
is an anonymous array of characters.
These are equivalent:
cout << "abc123" << '\n';
abc123
const char make_up_a_name[] = "abc123"; cout << make_up_a_name << '\n';
abc123
const char make_up_a_name[] = "abc123"; const char *p = &make_up_a_name[0]; cout << p << '\n';
abc123
"string literal"
is like an anonymous array.
if ("beta" < "alpha") // BAD CODE cout << "This is really quite surprising!\n";
c.cc:1: warning: comparison with string literal results in unspecified behavior This is really quite surprising!
"marx"
and "marx"
two arrays or one? Who knows‽
g++ -Wall
will detect this deplorable behavior.
To compare C-style strings, use the function strcmp. It has
a peculiar return value. strcmp(a,b)
returns:
a
<b
.
a
==b
.
a
>b
.
Why are you even considering using C-style strings?
std::string
sTo compare C++ std::string
values, or to compare a std::string
with a C-style string, use the usual operators:
< > <= >= == !=
Only Java geeks use std::string::compare()
,
which has the same three-way return value as strcmp.
Modified: 2017-02-04T17:46 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |