constexpr function as array size

有些话、适合烂在心里 提交于 2019-12-10 21:09:46

问题


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. But because j is not a constant expression, the second_array definition should be wrong. 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. Can rand() be evaluated at compile time? I think it can't be.


回答1:


Some compilers, such as GCC, allow C-style variable-length arrays as an extension to 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.




回答2:


in fact,

int second_array[f(j)];

will use non standard VLA (Varaible length array) extension.



来源:https://stackoverflow.com/questions/29674152/constexpr-function-as-array-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!