Abhinav Kushagra Abhinav Kushagra - 2 months ago 10
C++ Question

'Constant Expression Required' Error while keeping formal argument as a constant

This is a C++ programming code to display the values of array1 and array2 but I am getting a compile time error as 'Constant Expression Required'. Please Help

void display(const int const1 = 5)
{
const int const2 = 5;
int array1[const1];
int array2[const2];

for(int i = 1 ; i < 5 ; i++)
{
array1[i] = i;
array2[i] = i * 10;

std::cout << array1[i] << std::endl;
}
}

void main()
{
display(5);
}

Answer

In C++, const is not always constexpr. Back in the days, constexpr didn't exist, so the only way of having a compile time constant was to either use const with a literal, or to use enum, because both of these are easy for the compiler to check the value.

However, in C++11, we added constexpr, which guaranties that a constexpr variable has a value available at compile-time, and state that constexpr function can be evaluated aat compile time if all arguments are constexpr too.

In your code, you can write your variable const2 like this:

void display(const int const1=5)
{
    constexpr int const2 = 5;

    // ...
}

Now your code is much more expressive about what you are doing. instead of relying that the const may be available at compile time, you say "this variable has a value known at compile time, here's the value".

However, if you try to change const1, you'll get an error. Parameters, even with default value always as a value known at runtime. If the value is only known at runtime, you can't use it in template parameters or array size.

If you want your function to be able to receive the value const1 as a constant expression from where you can receive it as a template parameter, since template parameters are always known at compile time.

template<int const1 = 5>
void display()
{
    constexpr int const2 = 5;

    int array1[const1];
    int array2[const2];
}

You will have to call your function like that:

// const1 is 5
display();

// const1 is 10
display<10>();

If you want to know more about templates, go check Function templates, or this tutorial

Comments