In C++, empty() tells you whether a std::stack has no elements. It returns true for an empty stack and false when at least one element is waiting on top.
It is the safety check for the whole container. top() and pop() are undefined behavior on an empty stack, so you ask empty() first. A stack has no iterators, so while (!st.empty()) is also the normal way to walk through every element.
This function is a member function of std::stack<T>, declared in the <stack> header. It has been available since the first C++ standard, so every compiler supports it. You call it with a dot, for example st.empty(...).
Syntax
Call empty() on the stack. It takes no arguments and returns a bool.
C++
std::stack<int> st;
bool a = st.empty(); // true, nothing inside
st.push(7);
bool b = st.empty(); // false, one element inside
Call
What it does
st.empty()
Returns true if the stack has no elements, otherwise false. It never changes the stack.
empty() is fast and runs in constant time. It is the same as asking st.size() == 0, but it reads more clearly. Since C++20 the function is marked [[nodiscard]], so a compiler may warn if you call it and ignore the answer.
Library declarations
C++
[[nodiscard]] bool empty() const; // [[nodiscard]] since C++20
// stack<T, Container> from <stack>
// empty() returns c.empty()
Parameters
Parameter
Description
None
empty() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
true
The stack has no elements.
false
The stack has at least one element.
C++ Examples
Example 1 — Check an Empty Stack
A new stack is empty. After one push() it is not. Use std::boolalpha to print true and false.
topOr() receives the stack by const reference. empty() and the const overload of top() are both allowed.
For the empty stack, empty() is true, so the function returns the fallback -1 and never touches top().
For the filled stack, empty() is false, so top() is safe and returns the newest value 5.
Frequently Asked Questions
It returns true if the stack has no elements, and false if it has at least one element.
Calling top() or pop() on an empty stack is undefined behavior. A quick if (!st.empty()) check keeps your program safe.
A stack has no iterators. Use while (!st.empty()) { use st.top(); st.pop(); }. This also removes the elements one by one from the stack.
Yes. Both mean the stack holds no elements. empty() is the clearer way to write it and is the style most C++ programmers prefer.
There is no clear() function. Assign a new empty stack, such as st = std::stack<int>(); or swap with an empty one. Calling empty() afterwards returns true.