6

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

Z Qi
  • 61
  • 1
  • 3
  • Maybe this. VS doesn't claim to properly support `constexpr` https://msdn.microsoft.com/en-us/library/hh567368.aspx. – NutCracker Sep 21 '18 at 07:10
  • What `sqrt` are you calling? `std::sqrt` doesn't appear to be required to be a `constexpr` function. – John Ilacqua Sep 21 '18 at 07:30
  • Related: https://stackoverflow.com/questions/27744079/is-it-a-conforming-compiler-extension-to-treat-non-constexpr-standard-library-fu – John Ilacqua Sep 21 '18 at 07:35

3 Answers3

4

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

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
1

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.

user7860670
  • 35,849
  • 4
  • 58
  • 84
-2
  include cmath library since you using a sqrt() function 

http://www.cplusplus.com/reference/cmath/

ABO Baloyi
  • 17
  • 4