A function call must have a constant value in a constant expression

Viewed 3374

I have written a c++ program as blow:

#include <iostream>
int main()
{
    constexpr double a = 4.0;
    constexpr double b = sqrt(a);
    std::cout << b << std::endl;
    return 0;
}

When I tried to compile this code with visual studio 2017, I got an error that says a function call must have a constant value in a constant expression. The bad line is "constexpr double b = sqrt(a);".

But when I used g++ to compile the same code, no error was reported.

What's the reason of the error? What's the different between g++ and vc++?

3 Answers

sqrt isn't a constexpr function so can't be used in a constexpr expression. GCC seems to have a special built in version of sqrt which is constexpr. Clang doesn't allow this code either:

https://godbolt.org/z/SvFEAW

sqrt is required to be not a constant expression so constexpr double b = sqrt(a); is not supposed to work. Clang does not build this code as well. You also need to include <cmath> header in order to use this function.

Related