Search code examples
c++arraysconstantssize

How can I initialize an array of its length equal to the return of a const int method?


What I'm trying to accomplish is this:

inline const int size() { return 256; }

int main()
{
    int arr[size()];

    return 0;
}

But Visual Studio gives me an error when initializing arr[size()]:

expression must have a constant value

Is there a way to accomplish what I want without using global variables, Macros, std::vector or creating arr[ ] on heap?


Solution

  • Drop the inline and const and add constexpr specifier instead, to solve the issue:

    constexpr int size() { return 256; }
    

    now you can use it as array size like:

    int arr[size()];
    

    In C++ (not C) length of arrays must be known at compile time. const qualifier only indicates that a value must not change during running time of a program.

    By using constexpr you will specify that the output of the function is a known constant, even before the program execution.