Friday, December 9, 2022

C++: Using constant for array size

In C, you can use a constant when declaring an array:

  const n = 5;
  int a[n];

In C++, it would result in compile error "constant expression required". You have to declare it using constexpr:

  constexpr int n = 5;
  int a[n];

However, if you for example want to use the size of a vector to declare an array, you can't use the stack, you have to use the heap:

  int* a = new int[myVector.size()];
  ...
  delete[] a;

No comments:

Post a Comment