1

I defined a const int array like this :

const int arr[] = { 100 , 200, 300, 400 };

Now i want to set one of the elements of above array as the length of another array like the following :

char buffer[arr[3]];

But it gave me a compile time error :

non-constant arguments or reference to a non-constant symbol

I studied this This question to solve my problem but i became confuse about these questions :

  • Why can't i set an element of a const array as the length of another array?
  • Are the elements of a const array constant or read only?
  • What is the differences between a const and read only statements in c?

Regards!

2 Answers2

4

There are really two different kinds of constant "things" in C++.

The one that you know as the const keyword: you can't modify it at runtime.

And the one that's known as a constant value to the compiler at compile time.

That one would be:

constexpr int arr[] = { 100 , 200, 300, 400 };

C++ requires an array size to be a constexpr expression, and not just a const one. Some compilers let you get away with just a const size (and not even that, actually), but that's not the current C++ standard.

You might be wondering why, in this case, this is not a constant value at compile time. After all: it's right there. It's three digits. An integer. It can't go anywhere.

Well, that would be a different, pedantic question, but is mostly irrelevant. Your compiler is well within its rights to reject a non-constexpr expression in this case, as ill-formed. So it does. And you have no choice but to obey your compiler's demands.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0

I realized const and constexpr in the following statements :

  • const : To be evaluated at runtime and it's accepted by compiler and can't change in runtime.

    const int a = std::cin.get();       // correct
    const int b = 5;                    // correct
    
  • constexpr : To be evaluate at compile time

    constexpr int b = std::cin.get();   // incorrect (because it evaluate in compile time, so compiler cannot forecast the value at compile time)
    constexpr int b = 65;               // correct
    

Now in my code as i understood, i think the char buffer is evaluate the array size at compile time and const int arr will be avaluate at runtime. so cannot set char buffer array length with a number that will be evaluate at runtime and we need a constant value.

Notice :

const int arr[] = { 100 , 200, 300, 400 };     // Evaluate at runtime
char buffer[arr[3]];                           // Evaluate at compile time and cause error

So we need a const number that evaluated at compile time to set array length of the char buffer :

constexpr int arr[] = { 100 , 200, 300, 400 };     // Evaluate at compile time
char buffer[arr[3]];                               // Evaluate at compile time