C++ Array Library - back() Function


The C++ function std::array::back() Returns a reference to the last element of the array container. This method returns last array element itself, calling this method on empty array container will cause undefined behavior.


Following is the declaration for std::array::back() function form std::array header.

reference back();
const_reference back() const;



Return Value

Returns the last element of array container. If array object is const-qualified, the method return const reference otherwise it return reference.


If array size is non-zero then this member function never throws exception. Calling this memeber function on zero sized array will cause undefined behavior.

Time complexity

Constant i.e. O(1)


The following example shows the usage of std::array::back() function.

#include <iostream>
#include <array>

using namespace std;

int main(void) {
   array<int, 5> arr = {1, 2, 3, 4, 5};

   /* print last element */
   cout << "Last element of array                    = " << arr.back() 
      << endl;

   /* modify last element */
   arr.back() = 50;

   /* print modified array element */
   cout << "after modification last element of array = " << arr.back() 
      << endl;

   return 0;

Let us compile and run the above program, this will produce the following result −

Last element of array                    = 5
after modification last element of array = 50
Kickstart Your Career

Get certified by completing the course

Get Started