Home C++ Strings Functions rend() C++ std::string rend() Function Definition In C++, std::string::rend() is the stop marker for reverse iteration.
It does not point at a character you can read. 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 Compare reverse iterators with rend().
for (auto it = s.rbegin(); it != s.rend(); ++it) { } Call What it does s.rend()Reverse past-the-end iterator.
Never dereference rend().
Library declarations reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept; Parameters Parameter Description None rend() takes no parameters. Call it with empty brackets.
Return Value Return Value Description reverse_iterator Stop iterator for reverse loops.
C++ Examples 1. Reverse loop 2. Empty reverse 3. Build reversed Example 1 — Stop at rend() Print characters backwards.
#include <iostream>
#include <string>
int main() {
std::string s = "12";
for (auto it = s.rbegin(); it != s.rend(); ++it) {
std::cout << *it;
}
std::cout << '\n';
return 0;
} How It Works Iteration starts at rbegin(). It ends when it == rend(). Output is reversed. Example 2 — rbegin Equals rend Empty string reverse bounds match.
#include <iostream>
#include <string>
int main() {
std::string s;
std::cout << std::boolalpha << (s.rbegin() == s.rend()) << '\n';
return 0;
} How It Works No characters means reverse begin equals reverse end. The comparison is valid. Do not dereference either iterator here. Example 3 — Build a Reversed Copy Append characters while walking reverse iterators.
#include <iostream>
#include <string>
int main() {
std::string s = "top";
std::string rev;
for (auto it = s.rbegin(); it != s.rend(); ++it) {
rev.push_back(*it);
}
std::cout << rev << '\n';
return 0;
} How It Works We walk from last to first. Each character is pushed into rev. The new string is the reverse of the original. Frequently Asked Questions What is rend()? The end marker for reverse iteration—do not dereference it.
What pairs with rend()? rbegin() or crbegin().
Can I read *rend()? No. Undefined behavior.
Does rend() point at the first character? No. Reverse iterators that reach rend have moved past the first character.
Is there a const rend? Yes: crend().
Next: replace() Keep going through the string functions. Replace a slice of the string with new characters.
replace() tutorial → CODETOFUN NEWS
Stay Ahead in Tech Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
7 people found this page helpful
Helpful Share Copy link Suggestion