2
// since we can dedfine a static array like this
int a[5] = {0};
// decltype(a[5]) is `int [5]`

// Then how about this way?
constexpr int sum(int a, int b) { return a + b; }
int a, b;
std::cin >> a >> b;
int arr[sum(a, b)] = {0};

it can be compiled successfully, but is arr a static array? when I tried to print arr type with typeid().name() or boost::typeindex::type_id_with_cvr, I got below error:

error: cannot create type information for type 'int [(<anonymous> + 1)]' because it involves types of variable size
 std::cout << typeid(decltype(arr)).name() << std::endl;
3
  • It is not a static array unless you mark it as such. Commented Aug 8, 2018 at 8:27
  • 1
    a and b should be const also. Commented Aug 8, 2018 at 8:28
  • 1
    Declaring an array with size produced by sum invocation requires it to be invoked at compile time, for function sum to be evaluated to compile time both arguments are required to be known at compile time. Commented Aug 8, 2018 at 8:31

1 Answer 1

6

As the value of a and b are not known at compile time the result of sum is not a constexpr.

The code compiles presumably because you are using GCC which has an extension which allows declaring arrays on the stack with variable size, standard c++ doesn't allow this.

Sign up to request clarification or add additional context in comments.

1 Comment

Just a note that these are called variable length arrays (VLA): gcc.gnu.org/onlinedocs/gcc/Variable-Length.html. You can disable them with GCC by using -Werror=vla: wandbox.org/permlink/iJtZ5nmyDTaxFW2E.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.