C++ std::string cend() Function

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

Definition

In C++, std::string::cend() returns a const_iterator to one past the last character.

Pair it with cbegin() for read-only loops. 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 stop iterator for const walks.

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

Never dereference cend().

Library declarations
C++
const_iterator cend() const noexcept;

Parameters

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

Return Value

Return ValueDescription
const_iteratorPast-the-end const iterator.

C++ Examples

Example 1 — cbegin Equals cend

Detect an empty string.

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

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

How It Works

  1. An empty string has equal cbegin and cend.
  2. The comparison is safe.
  3. empty() is still the usual API for this check.

Example 2 — Print Until cend()

Walk every character.

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

int main() {
    std::string s = "Hi";
    for (auto it = s.cbegin(); it != s.cend(); ++it) {
        std::cout << *it << '-';
    }
    std::cout << '\n';
    return 0;
}

How It Works

  1. Iteration stops at cend().
  2. Each character prints with a dash.
  3. No writes happen through the iterator.

Example 3 — Count With Distance

Distance from cbegin to cend.

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

int main() {
    std::string s = "seven";
    std::cout << std::distance(s.cbegin(), s.cend()) << '\n';
    return 0;
}

How It Works

  1. Distance counts characters in the range.
  2. Result matches size().
  3. Prefer size() for clarity when that is all you need.

Frequently Asked Questions

A const iterator one past the last character.
No.
As the end marker for read-only iteration with cbegin().
Yes in effect—both are const past-the-end iterators.
C++11.

Next: clear()

Keep going through the string functions. Remove all characters; size becomes 0.

clear() 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.

8 people found this page helpful