14 Beginner The Hundred
Adding to a String Literal
the + that takes away
#include <iostream>
int main() {
int week = 1;
std::cout << "week " + week << '\n';
auto greeting = "hello" + 2;
std::cout << greeting << '\n';
}
Run it. What does it print?
Answer
No numbers anywhere — both strings lost their fronts instead. (Yes, eek — the
output is as alarmed as you are.)
Why¶
A string literal is not a std::string — it's a const char[N], which decays to a
plain const char* the moment you use it in arithmetic. So + here is pointer
arithmetic: "week " + 1 doesn't append the number, it returns a pointer one
character into the array, and printing from there gives eek (trailing space and
all). Likewise auto greeting = "hello" + 2; deduces const char*, not any kind of
string — it just points at llo. Adding a char is worse: "abc" + 'A' offsets by
65, sailing far past the end of a 4-element array — that's undefined behavior,
and whatever gets printed (if anything) is not guaranteed; it may even appear to work.
GCC compiles all of this silently even with -Wall -Wextra; Clang at least tells you
adding 'int' to a string does not append to the string (-Wstring-plus-int).
The fix¶
Make one operand an actual std::string and + means concatenation again — the s
suffix (C++14, from std::string_literals) does it right at the literal:
std::cout << "week " + std::to_string(week) << '\n'; // week 1
using namespace std::string_literals;
auto greeting = "hello"s + " there"; // a real std::string
Takeaway: + on a string literal moves a pointer, it never appends — make one
side a std::string before you concatenate.
Try it: g++ -std=c++17 main.cpp -o demo && ./demo