Static Arrays using std::array

Array Initialization

What are the different ways to initialize a std::array in C++?

Abstract art representing computer programming

There are several ways to initialize a std::array in C++:

Default initialization

In this example, we create an array of 5 integers, with each element default-initialized. For int, this means they are initialized with a value of 0:

std::array<int, 5> MyArray;

Initialization with specific values

This creates an array of 5 integers, with the elements initialized to the specified values:

std::array<int, 5> MyArray{1, 2, 3, 4, 5};

Initialization with fewer values than the array size

Below, we provide initialisation for some of the values. The remaining elements will be value-initialized. For primitive types like int, this means they will be zero-initialized.

std::array<int, 5> MyArray{1, 2, 3};

Initialization with class template argument deduction (CTAD)

In this example, the compiler deduces the type and size of the array based on the initializer list.

std::array MyArray{1, 2, 3, 4, 5};

Default initialization with empty braces

In the following example, all elements will be value-initialized (zero-initialized in the case of int):

std::array<int, 5> MyArray{};

Remember that std::array has a fixed size known at compile time, so you must specify the size when declaring the array, unless you use CTAD.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved