Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...