0

I tried to execute two different scenarios :

Scenario 1:

const auto arraySize = 10; // fine, arraySize is constant 
std::array<int, arraySize> data;

Here , arraySize is treated as compile time constant and hence it was allowed in std::array .

Scenario 2:

int sz=10;
const auto arraySize = sz; // fine .
std::array<int, arraySize> data; //error , arraySize is not compile time constant .

In scenario 2 , arraySize is not treated as compile time constant despite of the fact that arrySize is a constant copy of sz .

Why these two scenarios were treated differently ?

SACHIN GOYAL
  • 955
  • 6
  • 19
  • 2
    `arraySize` is a constant copy of something that is *not* constant...? – DevSolar Jan 21 '16 at 09:38
  • 2
    Because `const` doesn't mean "compile time constant". In certain cases it can be compile-time, but it's not guaranteed and therefore you cannot use them in contexts which require compile-time constants. Use `constexpr` instead! – Tamás Zahola Jan 21 '16 at 09:39

2 Answers2

3

Because it can be like

int sz = 0;
std::cin >> sz;
const auto arraySize = sz;

and here value of sz is defined in runtime. You can use constexpr, instead of const, than will be compile error on such initialization.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
0

You probably should consider using constexpr.

int sz=10; is a variable set to some constant. The compiler may be clever enough (or not!) to constant propagate it when optimizing.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547