3

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
  • 1
    If you are using gcc then what you are actually getting is a VLA. Commented Apr 16, 2015 at 12:07

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I used Ideone.com, so it's probably GCC. So to my understanding, the array is allocated at run time, and deallocated when the block finishes. Were the VLA not available, the C++11 standard would not allow it. Is that correct?
1

in fact,

int second_array[f(j)];

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.