简体   繁体   中英

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. 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.

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 .

in fact,

int second_array[f(j)];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM