C++ std::string crend() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::string

Definition

In C++, std::string::crend() marks the end of a read-only reverse walk.

Include <string>. (C++11)

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

Use as the end condition with crbegin().

C++
for (auto it = s.crbegin(); it != s.crend(); ++it) { }
CallWhat it does
s.crend()Const reverse past-the-end iterator.

Never dereference crend().

Library declarations
C++
const_reverse_iterator crend() const noexcept;

Parameters

ParameterDescription
Nonecrend() takes no parameters. Call it with empty brackets.

Return Value

Return ValueDescription
const_reverse_iteratorStop marker for const reverse loops.

C++ Examples

Example 1 — Loop to crend()

Print a word backwards.

C++
#include <iostream>
#include <string>

int main() {
    std::string s = "on";
    for (auto it = s.crbegin(); it != s.crend(); ++it) {
        std::cout << *it;
    }
    std::cout << '\n';
    return 0;
}

How It Works

  1. The loop stops at crend().
  2. Characters print in reverse.
  3. No modification occurs.

Example 2 — crbegin Equals crend

Empty string check.

C++
#include <iostream>
#include <string>

int main() {
    std::string s;
    std::cout << std::boolalpha << (s.crbegin() == s.crend()) << '\n';
    return 0;
}

How It Works

  1. Empty means reverse begin equals reverse end.
  2. Comparison is fine.
  3. Do not dereference.

Example 3 — Distance crbegin→crend

Count characters via reverse const iterators.

C++
#include <iostream>
#include <iterator>
#include <string>

int main() {
    std::string s = "five!";
    std::cout << std::distance(s.crbegin(), s.crend()) << '\n';
    return 0;
}

How It Works

  1. Distance along reverse iterators still counts elements.
  2. Result equals size().
  3. Use size() when that is the real goal.

Frequently Asked Questions

It is the end marker for const reverse iteration.
No.
crbegin().
C++11.
Same role: a reverse past-the-end iterator.

Next: data()

Keep going through the string functions. Pointer to the string’s contiguous character buffer.

data() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful