Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function call must have a constant value in a constant expression [duplicate]

Tags:

c++

visual-c++

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++?

like image 456
Z Qi Avatar asked Oct 16 '22 13:10

Z Qi


1 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

like image 73
Alan Birtles Avatar answered Oct 29 '22 17:10

Alan Birtles