stack empty() and stack size() in C++ STL (original) (raw)

Last Updated : 08 Apr, 2025

The std::stack::size() and **std::stack::empty() in C++ are built-in functions that are used to provide information about the size of the stack. They are the member functions of the std::stack container defined inside header file.

**stack::empty()

The **stack::empty() method is used to check whether the stack is empty or not.

C++ `

// C++ program to illustrate how to use // stack::empty() function #include <bits/stdc++.h> using namespace std;

int main() { stack st;

  // Checking if the stack st is empty
if (st.empty())
    cout << "Stack is Empty" << endl;
else
    cout << "Stack is NOT Empty" << endl;

// Inserting an element
st.push(11);

  // Again checking if the stack st is empty
if (st.empty())
    cout << "Stack is Empty" << endl;
else
    cout << "Stack is NOT Empty" << endl;

return 0;

}

`

Output

Stack is Empty Stack is NOT Empty

Syntax

st.**empty();

**Parameters

**Return Value

stack::size()

The **stack::size() method is used to find the number of elements in the stack container.

C++ `

// C++ program to illustrate how to use stack::size() #include <bits/stdc++.h> using namespace std;

int main() { stack st;

st.push(11);
st.push(13);
st.push(9);

// Finding the size of the stack st
int n = st.size();
  cout << "Size : " << n << endl;


return 0;

}

`

Syntax

st.**size();

**Parameters

**Return Value

**Difference Between stack::size() and stack::empty()

Both the **stack::size() and **stack::empty() methods are give the information about the size of stack, but there are some differences between them which are listed below:

**stack::empty() **stack::size()
It is used to return whether the stack is empty or not. It is used to return the number of elements in the stack.
Its syntax is:-**stack_name.empty(); Its syntax is:-**stack_name.size();
Its return type is of boolean. Its return type is of integer.