1

While investigating the constexpr keyword in C++, I've come up with the following code:

#include <iostream>

int main() {
    const int n  = 10;
    constexpr int n2 = 10;

    int a1[n];
    int a2[n2];

    std::cout << "n " << n << std::endl;
    std::cout << "n2 " << n2 << std::endl;
}

I would expect that declaring the array a1 with "const" would not work and the compiler would at least give me a warning (assuming the compilation is done with g++ -Wall -pedantic constexpr_1.cpp -o ce1) but it does not. I've seen some error with VS compiler so any hint is welcome here.

sydh
  • 11
  • 1
  • 1
    The size of an array must be known at compile time and both `n` and `n2` are known at compile time and can't be modified at runtime, at least not in a legal way. Maybe [this question](https://stackoverflow.com/questions/13346879/const-vs-constexpr-on-variables) is interesting for you. – Lukas-T Apr 08 '20 at 08:35

1 Answers1

0

In C++, the size of each array dimension in an array declaration must be an integral constant expression.

A constant expression (with some exceptions) is a value that can be evaluated at compile-time. That includes const variables with automatic storage duration initialized by a constant expression [ref].

Therefore both const int n = 10; and constexpr int n2 = 10; are usable as a size in array declarations and the code example is valid.

Note: this is not the case in C - so make sure to compile in C++ mode [ref].

The code also compiles fine in MSVC 2015+. But it could very well be that an archaic VC++ compiler has a bug that prevents this from compiling.

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • Ok thanks for the answer. I've been confused by this article: https://smartbear.com/blog/develop/using-constexpr-to-improve-security-performance-an/ which states that the compiler should warn something like: //compilation error: “constant expression required”. – sydh Apr 09 '20 at 07:48