In C++, std::string::front() returns a reference to the first character of the string.
The string must not be empty. Check empty() first. 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
Call with empty brackets on a non-empty string.
C++
char c = s.front();
s.front() = 'A';
Call
What it does
s.front()
Reference to the first character.
Same idea as s.at(0) when the string is non-empty, but front() does not throw—calling it on an empty string is undefined behavior.
Library declarations
C++
char& front();
const char& front() const;
Parameters
Parameter
Description
None
front() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
char&
Reference to character 0. Const overload returns const char&.
C++ Examples
Example 1 — Basic front()
Print the first character.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "Hello";
std::cout << s.front() << '\n';
return 0;
}
Output
H
How It Works
The string starts with 'H'.
front() returns a reference to that character.
Printing it shows H.
Example 2 — Assign front()
Change the first letter in place.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "cat";
s.front() = 'b';
std::cout << s << '\n';
return 0;
}
Output
bat
How It Works
front() refers to the first character 'c'.
Assigning 'b' updates it.
The string becomes "bat".
Example 3 — Check Before front()
Skip front() when the string is empty.
C++
#include <iostream>
#include <string>
int main() {
std::string s;
if (s.empty()) {
std::cout << "empty\n";
} else {
std::cout << s.front() << '\n';
}
s = "Z";
if (!s.empty()) {
std::cout << s.front() << '\n';
}
return 0;
}
Output
empty
Z
How It Works
The first string is empty, so we print a message instead of calling front().
After assigning "Z", the string has one character.
front() safely returns 'Z'.
Frequently Asked Questions
A reference to the first character of a non-empty string.
Calling front() is undefined behavior. Check empty() first.
For a non-empty string, both refer to the first character. at(0) throws on empty; front() does not throw—it is undefined.