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

Viewed 146

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?

4 Answers

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.

Looks like error message is confusing you. The problem is you do not need a constant value as message says but constant expression:

Defines an expression that can be evaluated at compile time.

Such expressions can be used as non-type template arguments, array sizes, and in other contexts that require constant expressions, e.g.

and to achieve that you can add constexpr specifier:

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time. Such variables and functions can then be used where only compile time constant expressions are allowed (provided that appropriate function arguments are given).

to your function allowing compiler to evaluate it as constant expression

 constexpr const int size() { return 256; }

Note: declaring return type by value as const does not really make any difference so you can simply remove that.

You can replace const with constexpr as others have pointed out, but I should add that your original code compiles fine using the G++ compiler because it supports variable-length arrays, unlike Microsoft's compiler.

From C++20, you can also make size an immediate function, i.e. a function that is guaranteed to be evaluated at compile time.

consteval int size() { return 256; }
Related