std::basic_string<CharT,Traits,Allocator>::back

Returns reference to the last character in the string. The behavior is undefined if empty() is true.

# Declarations

CharT& back();

(constexpr since C++20)

const CharT& back() const;

(constexpr since C++20)

# Return value

Reference to the last character, equivalent to operator[](size() - 1).

# Notes

In libstdc++, back() is not available in C++98 mode.

# Example

#include <iostream>
#include <string>
 
int main()
{
    std::string s("Exemplary");
    char& back1 = s.back();
    back1 = 's';
    std::cout << s << '\n'; // "Exemplars"
 
    std::string const c("Exemplary");
    char const& back2 = c.back();
    std::cout << back2 << '\n'; // 'y'
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 534C++98std::basic_string did not have the member function back()added

# See also