C++ std::array::back

The std::array::back function provides access to the last element of a std::array. If the array is empty, the behavior is undefined, so it should only be used when the array contains at least one element.


Syntax of std::array::back

</>
Copy
reference back();
const_reference back() const;

Parameters

The std::array::back function does not take any parameters.

Return Value

Returns a reference to the last element of the array. If the array is const, the returned reference is also const.

Exceptions

The std::array::back function does not throw exceptions. However, using it on an empty array leads to undefined behavior.


Examples for std::array::back

Example 1: Accessing the Last Element Using std::array::back

This example demonstrates how to use the back function to access the last element of a std::array:

</>
Copy
#include <iostream>
#include <array>

int main() {
    std::array<int, 5> arr = {10, 20, 30, 40, 50};

    std::cout << "The last element is: " << arr.back() << std::endl;

    arr.back() = 100; // Modify the last element
    std::cout << "The modified last element is: " << arr.back() << std::endl;

    return 0;
}

Explanation:

  1. A std::array named arr is initialized with the elements {10, 20, 30, 40, 50}.
  2. The back() function is used to access the last element of the array, which is 50.
  3. The value of the last element is modified using arr.back() = 100.
  4. The modified value of the last element (100) is displayed.

Output:

The last element is: 50
The modified last element is: 100

Example 2: Undefined Behavior with an Empty Array

Without Exception Handling

This example shows what happens when back() is used on an empty array:

</>
Copy
#include <iostream>
#include <array>

int main() {
    std::array<int, 0> arr; // Empty array

    // Accessing back() on an empty array (undefined behavior)
    std::cout << "The last element is: " << arr.back() << std::endl;

    return 0;
}

Explanation:

Since the array is empty, calling back() results in undefined behavior, potentially causing the program to crash or output garbage values.

Output:

[Undefined behavior: may crash or output garbage]

With Exception Handling

This example demonstrates how to check if the array is empty before calling back():

</>
Copy
#include <iostream>
#include <array>

int main() {
    std::array<int, 0> arr; // Empty array

    if (!arr.empty()) {
        std::cout << "The last element is: " << arr.back() << std::endl;
    } else {
        std::cout << "The array is empty. No last element to access." << std::endl;
    }

    return 0;
}

Explanation:

  1. The program checks if the array is empty using empty().
  2. If the array is not empty, back() is called to access the last element.
  3. If the array is empty, a message is displayed, avoiding undefined behavior.

Output:

The array is empty. No last element to access.