In C++, std::string::back() returns a reference to the last character of the string.
The string must not be empty. Include <string>.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax
Call with empty brackets on a non-empty string.
C++
char c = s.back();
s.back() = '!';
Call
What it does
s.back()
Reference to the last character.
Often paired with push_back / pop_back. After pop_back, do not use an old reference from back().
Library declarations
C++
char& back();
const char& back() const;
Parameters
Parameter
Description
None
back() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
char&
Reference to the last character.
C++ Examples
Example 1 — Basic back()
Print the last character.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "Code";
std::cout << s.back() << '\n';
return 0;
}
Output
e
How It Works
"Code" ends with 'e'.
back() returns that character.
The rest of the string is unchanged.
Example 2 — Assign back()
Replace the final character.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "fun.";
s.back() = '!';
std::cout << s << '\n';
return 0;
}
Output
fun!
How It Works
The last character was '.'.
Assignment through back() replaces it with '!'.
The printed string shows the update.
Example 3 — back() Then pop_back()
Read the last char, then remove it.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "abX";
std::cout << "last: " << s.back() << '\n';
s.pop_back();
std::cout << s << '\n';
return 0;
}
Output
last: X
ab
How It Works
back() reads 'X' without removing it.
pop_back() then deletes the last character.
The string left is "ab".
Frequently Asked Questions
It returns a reference to the last character of a non-empty string.
No. It is undefined behavior. Check empty() first.
back() reads or changes the last character. pop_back() removes it.
For a non-empty string, yes they refer to the same character. at throws if size is 0; back does not throw.
You can, but the pointer becomes invalid if the string reallocates or the character is removed.