C++ Stack push() Function

Last Updated : 12 May 2026

Stack push() Function

C++ Stack push () function is used for adding new elements at the top of the stack. If we have an array of type stack and by using the push() function we can insert new elements in the stack. The elements are inserted at the top of the stack. The element which is inserted most initially is deleted at the end and vice versa as stacks follow LIFO principle.

Syntax

It has the following syntax:

Parameters

value: The parameter represents the value to which the element is initialized. The parameter specifies the value of the newly inserted element. The element 'val' becomes the new top element of the stack after function execution.

Return Value

The function only inserts element and does not return any value. The return type of the function can be thought as void.

Example of Stack push() Function

Here, we are going to discuss several examples of stack push() function.

Example 1: Insert Integer Elements into a Stack Using push()

This example demonstrates how to insert integer elements into a stack using the push() function.

Output:

Poping the elements out of the stack..... 4 3 2 1 0

Example 2: Add and Display Stack Elements Using push()

This example demonstrates how to add elements into a stack using the push() function and display them in LIFO order.

Output:

90 85 80 79 69

Example 3: Remove Stack Elements After Insertion Using push()

This example demonstrates how to insert elements into a stack using the push() function and remove them using pop().

Output:

Popping out elements... 22 11  

Example 4: Check Stack Size After Insertion Using push()

This example demonstrates how to insert elements into multiple stacks using the push() function and check their sizes.

Output:

Size of a: 3
Size of b:2 

Complexity

One call is made to the push back on the container that is underlying, which is necessary for the insertion operation on the element to get completed.

Data races

The modification is made to the container, and the elements contained. The addition of a new element modifies all the underlying stack elements.

Exception Safety

Guarantee as equivalent to the operations that are performed on the underlying container object is provided.


Next TopicC++ Stack