I need to use cmath's abs() function, but Visual Studio says it's overloaded and I can't even use something like this:
unsigned a = 5, b = 10, c;
c = abs(a-b);
I don't know how to use it properly.
I need to use cmath's abs() function, but Visual Studio says it's overloaded and I can't even use something like this:
unsigned a = 5, b = 10, c;
c = abs(a-b);
I don't know how to use it properly.
You can use the ternary operator:
As you can see here, there is no cmath function
abs
that takes an unsigned integer. This is because unsigned integers are never negative. Try doing the following instead:In this case,
c = 5
as expected.The versions in
<cmath>
are for floating point types, so there is no unambiguously best match. The overload for integral types are in<cstdlib>
, so one of those will yield a good match. If you are usingabs
on different types, you can use both includes and let overload resolution do its work.On the other hand, this doesn't yield correct code, since the expression
a-b
does not invoke integer promotion, so the result is anunsigned int
. The real solution is to use signed integral types for differences, as well as the integral typestd::abs
overloads.