Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a bug in std::gcd?

I've come across this behavior of std::gcd that I found unexpected:

#include <iostream>
#include <numeric>

int main()
{
    int      a = -120;
    unsigned b =  10;

    //both a and b are representable in type C
    using C = std::common_type<decltype(a), decltype(b)>::type;
    C ca = std::abs(a);
    C cb = b;
    std::cout << a << ' ' << ca << '\n';
    std::cout << b << ' ' << cb << '\n';

    //first one should equal second one, but doesn't
    std::cout << std::gcd(a, b) << std::endl;
    std::cout << std::gcd(std::abs(a), b) << std::endl;
}

Run on compiler explorer

According to cppreference both calls to std::gcd should yield 10, as all preconditions are satisfied.

In particular, it is only required that the absolute values of both operands are representable in their common type:

If either |m| or |n| is not representable as a value of type std::common_type_t<M, N>, the behavior is undefined.

Yet the first call returns 2. Am I missing something here? Both gcc and clang behave this way.

like image 977
perivesta Avatar asked Dec 17 '19 17:12

perivesta


1 Answers

Looks like a bug in libstc++. If you add -stdlib=libc++ to the CE command line, you'll get:

-120 120
10 10
10
10
like image 146
Marshall Clow Avatar answered Oct 14 '22 14:10

Marshall Clow