本文介绍了可以使用 const 变量而不是 constexpr 的大小来声明数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个 C++ 代码正确吗?

Is this C++ code correct?

const size_t tabsize = 50;
int tab[tabsize];

问题是我已经看到了很多关于这件事的相互矛盾的意见.甚至 ##c++ IRC 频道和编程论坛的人们也声称完全不同的东西.

The problem is that I've already seen numerous conflicting opinions on that matter. Even people at ##c++ IRC channel and programming forums claim radically different things.

有人说上面的代码是正确的.

Some people say the above code is correct.

其他人争辩说它不是,它应该是这样的:

Others argue that it is not, and that it should necessarily be like this:

constexpr size_t tabsize = 50;
int tab[tabsize];

既然我已经对C++ 专家"的相互矛盾的意见感到困惑,我可以要求一个合理的支持答案吗?非常感谢!

Since I'm already confused enough by conflicting opinions of "C++ experts", could I please ask for a reasonably backed up answer? Many thanks!

推荐答案

在 C++ 中,整数的处理方式与其他常量类型不同.如果它们是用编译时常量表达式初始化的,则它们可以在编译时表达式中使用.这样做了(在 C++ 的开头,当 constexpr 不存在时)所以数组大小可以是 const int 而不是 #defined(就像你被迫在 C 中一样):

In C++ constant integers are treated differently than other constant types. If they are initialized with a compile-time constant expression they can be used in a compile time expression. This was done (in the beginning of C++, when constexpr didn't exist) so that array size could be a const int instead of #defined (like you were forced in C):

(假设没有 VLA 扩展)

const int s = 10;
int a[s];          // OK in C++

const int s2 = read(); // assume `read` gets a value at run-time
int a2[s2];       // Not OK

int x = 10;
const int s3 = x;
int a3[s3];       // Not OK

所以答案是肯定的,您可以使用 const 整数变量作为数组的大小如果它是由编译时常量表达式初始化的

So the answer is yes, you can use a const integer variable as the size of an array if it was initialized by a compile time constant expression

这是另一个问题的我的回答.这个问题是关于 int vs float constconstexpr,所以不完全是重复的,但答案适用于这里非常好.

This is my answer from another question. That question is about int vs float const and constexpr, so not exactly a duplicate, but the answer applies here very nicely.

这篇关于可以使用 const 变量而不是 constexpr 的大小来声明数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 18:00
查看更多