1

std::sqrt (and similarly std::hypot and other <cmaths> functions) are not (yet) constexpr.

So, basically why does this work in gcc?

#include <cmath>

int main() {
    static constexpr double root2 = std::sqrt(10);
    static constexpr int int_root2 = static_cast<int>(root2);
    static_assert(int_root2 == 3);
    return int_root2;
}

Works in gcc, but not in clang, which throws the expected

error: constexpr variable 'root2' must be initialized by a constant expression
    static constexpr double root2 = std::sqrt(10);

Godbolt comparison

Simply: gcc functionality that is outside (beyond) the standard and can't be relied upon?

Update:

From the comments below:

if we pass -fno-builtin to gcc and change the argument to std:sqrt to 10.0 then gcc throws an error, because its builtin for ints is constexpr. Possible duplicate

Oliver Schönrock
  • 1,038
  • 6
  • 11

0 Answers0