Bart
Bart

Reputation: 460

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.

Upvotes: 3

Views: 2288

Answers (2)

Jarod42
Jarod42

Reputation: 217275

in fact,

int second_array[f(j)];

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

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254461

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.

Upvotes: 4

Related Questions