[英]constexpr function as array size
I'm trying to figure out why my code compiles, when it shouldn't: 我试图弄清楚为什么我的代码编译,当它不应该:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
constexpr int ret_one()
{
return 1;
}
constexpr int f(int p)
{
return ret_one() * p;
}
int main() {
int i = 2;
srand(time(0));
int j = rand();
int first_array[f(10)]; // OK - 10 is a constant expression
int second_array[f(j)]; // Error - the parameter is not a constant expression
j = f(i); // OK - doesn't need to be constexpr
std::cout << sizeof(second_array);
return 0;
}
So the first_array
definition is OK. 所以
first_array
定义没问题。 But because j
is not a constant expression, the second_array
definition should be wrong. 但是因为
j
不是常量表达式,所以second_array
定义应该是错误的。 On each program run I'm getting different array sizes. 在每个程序运行中,我得到不同的数组大小。 Is that how it's supposed to work?
它是如何工作的? In my book the author clearly states that a constepxr is an expression whose value can be evaluated at compile time.
在我的书中,作者清楚地指出constepxr是一个表达式,其值可以在编译时进行评估。 Can
rand()
be evaluated at compile time? 可以在编译时评估
rand()
吗? I think it can't be. 我认为不可能。
Some compilers, such as GCC, allow C-style variable-length arrays as an extension to C++. 一些编译器(如GCC)允许C风格的可变长度数组作为C ++的扩展。 If your compiler does that, then your code will compile.
如果您的编译器这样做,那么您的代码将编译。
If you're using GCC, then you can enable a warning with -Wvla
or -pedantic
. 如果您正在使用GCC,则可以使用
-Wvla
或-pedantic
启用警告。
in fact, 事实上,
int second_array[f(j)];
will use non standard VLA (Varaible length array) extension. 将使用非标准VLA(可变长度阵列)扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.