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;
}
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.
-120 % 10u
? (Hint: it's not 0.) Yes, bug. – Mandle-120
tounsigned
will result in4294967176
which% 10u
is6
. My question was rather if this behavior is indeed incorrect, which it seems to be. – Goshunsigned
, so no bug either – Gosh