问题描述
这是C ++ code正确吗?
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.
有人说上面的code是正确的。
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 ++中恒整数比其他类型不变区别对待。如果它们与编译时间常数前pression初始化它们可以在编译时前pression使用。这样做(在 C ++
,当 constexpr
不存在的开始),使数组的大小可能是一个 const int的
而不是的#define
D(就像你不得不在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 #define
d (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整型变量作为数组的大小如果它是由编译时间常数前pression初始化
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 浮动
常量
和 constexpr
,所以不完全重复,但答案适用于这里非常漂亮。
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声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!