C++ std::string pop_back() Function

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

Definition

In C++, std::string::pop_back() removes the last character.

The string must not be empty. 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

Call on a non-empty string.

C++
s.pop_back();
CallWhat it does
s.pop_back()Erase the last character.

Check !s.empty() before calling.

Library declarations
C++
void pop_back();

Parameters

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

Return Value

Return ValueDescription
voidNo return value.

C++ Examples

Example 1 — Basic pop_back()

Drop the last character.

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

int main() {
    std::string s = "cat!";
    s.pop_back();
    std::cout << s << '\n';
    return 0;
}

How It Works

  1. The last character is '!'.
  2. pop_back() removes it.
  3. Left with "cat".

Example 2 — Pop While Condition

Remove trailing spaces.

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

int main() {
    std::string s = "hi  ";
    while (!s.empty() && s.back() == ' ') {
        s.pop_back();
    }
    std::cout << '[' << s << "]\\n";
    return 0;
}

How It Works

  1. We loop while the last character is a space.
  2. Each pop_back shortens the string.
  3. Trailing spaces are gone.

Example 3 — Safe Pop

Only pop when not empty.

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

int main() {
    std::string s;
    if (!s.empty()) {
        s.pop_back();
    } else {
        std::cout << "nothing to pop\\n";
    }
    return 0;
}

How It Works

  1. The string is empty.
  2. We skip pop_back to avoid undefined behavior.
  3. A message explains the situation.

Frequently Asked Questions

It removes the last character of a non-empty string.
Undefined behavior. Check empty() first.
No. Read back() first if you need the value, then pop_back().
C++11.
Usually not. Only size decreases.

Next: push_back()

Keep going through the string functions. Append one character at the end.

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

13 people found this page helpful