Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 489
Bart Avatar asked Jun 25 '26 20:06

Bart


2 Answers

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.

like image 82
Mike Seymour Avatar answered Jun 28 '26 10:06

Mike Seymour


in fact,

int second_array[f(j)];

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

like image 42
Jarod42 Avatar answered Jun 28 '26 10:06

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!