Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

constant
data structures
keyword
initialize

How to create an N-element constexpr array in C++

Educative Answers Team

A constexpr variable is used when its value is supposed to be constant throughout a program’s execution. The constexpr keyword computes the value of such a variable during compilation, and the compiler looks to see if it can detect any changes to that variable.

svg viewer

Manual initialization

A constexpr array can be declared and initialized manually through:

constexpr int arr[3] = {1,2,3};

However, manually initializing a large array can become tiresome.

Using struct

For example, to initialize an integer array of size nn, with integers from 00 to n1n-1, a struct is declared that has an int array. This array is then initialized using a constexpr constructor.

A template with non-type parameters has been used in the code below to declare an array of a particular size.

Code

#include <iostream>
using namespace std;

template<int size>
struct ConstArray{
  int arr[size];

  // 'constexpr' constructor:
  constexpr ConstArray():arr(){
    for(int i = 0; i < size; i++)
      arr[i] = i;
  }

  // This member function should have 'const':
  void print() const{
    for(int i = 0; i < size; i++)
      cout << arr[i] << endl;
  }
};

int main() {
  constexpr int n = 5;
  constexpr ConstArray arr = ConstArray<n>();
  arr.print();

  return 0;
}

RELATED TAGS

constant
data structures
keyword
initialize
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring