Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::abs for "unsigned long long int" data type

Why should I get this error

 C2668: 'abs' : ambiguous call to overloaded function

For a simple code like this

#include <iostream>
#include <cmath>
int main()
{
  unsigned long long int a = 10000000000000;
  unsigned long long int b = 20000000000000;
  std::cout << std::abs(a-b) << "\n";   // ERROR
  return 0;
}

The error still presents after removing std::. However if I use int data type (with smaller values) there is no problem.

The traditional solution is to check that manually

std::cout << (a<b) ? (b-a) : (a-b) << "\n";

Is that the only solution?

like image 265
mahmood Avatar asked Jun 19 '13 10:06

mahmood


People also ask

What is unsigned long long int?

Description. Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).

How many digits can unsigned long long int hold?

It takes a size of 64 bits. A maximum integer value that can be stored in an unsigned long long int data type is 18, 446, 744, 073, 709, 551, 615, around 264 – 1(but is compiler dependent).

What is the difference between an unsigned long long and an unsigned long long int?

So on your compiler, an int and a long might be the same, but this isn't universal across compilers. As for the difference between unsigned long and long : Assuming 4 bytes, a long has the range of -2,147,483,648 to 2,147,483,647 . An unsigned long has the range of 0 to 4,294,967,295 .


2 Answers

The check seem the only really good solution. Alternatives require type bigger than yours and nonstandard extension to use it.

You can go with solutions casting to signed long long if your range fits. I would hardly suggest that way, especially if the implementation is placed in a function that does only that.

like image 124
Balog Pal Avatar answered Oct 23 '22 00:10

Balog Pal


You are including <cmath> and thus using the "floating-point abs".

The "integer abs" is declared in <cstdlib>.

However, there is no overload for unsigned long long int (both a and b are, thus a-b is, too), and the overload for long long int only exists since C++11.

like image 26
gx_ Avatar answered Oct 23 '22 00:10

gx_