Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
997 views
in Technique[技术] by (71.8m points)

c++ - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...