Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can integer type int64_t not hold this legal value? [duplicate]

I'm trying to write a test case for some corner case. For input of type int64_t, the following line won't compile:

int64_t a = -9223372036854775808LL;

The error/warning is:

error: integer constant is so large that it is unsigned [-Werror]

I thought the number was out of range, so I tried:

std::cout << std::numeric_limits<int64_t>::min() << std::endl;

It outputs exactly the same number!!! So the constant is within the range.

How can I fix this error?

like image 892
fluter Avatar asked Jul 19 '19 04:07

fluter


People also ask

What is int64_t data type in C++?

A long on some systems is 32 bits (same as an integer), the int64_t is defined as a 64 bit integer on all systems (otherwise known as a long long). Portability may be affected using long, but using int64_t looks like it was created to increase portability.

Can an int hold a pointer?

For now, we just need to know how to link a pointer to the address of a variable. Important point to note is: The data type of pointer and the variable must match, an int pointer can hold the address of int variable, similarly a pointer declared with float data type can hold the address of a float variable.

Should I use long long or int64_t?

If long long is present, it must have at least 64 bits, so casting from (u)int64_t to (unsigned) long long is value-preserving. If you need a type with exactly 64 bits, use (u)int64_t , if you need at least 64 bits, (unsigned) long long is perfectly fine, as would be (u)int_least64_t .

Is int64_t same as long?

In a 64-bit compile, int64_t is long int , not a long long int (obviously).


Video Answer


2 Answers

You may write

int64_t a = -1 - 9223372036854775807LL;

The problem is that the - is not part of the literal, it is unary minus. So the compiler first sees 9223372036854775808LL (out of range for signed int64_t) and then finds the negative of this.

By applying binary minus, we can use two literals which are each in range.

like image 79
Ben Voigt Avatar answered Oct 10 '22 19:10

Ben Voigt


Ben's already explained the reason, here's two other possible solutions.

Try this

int64_t a = INT64_MIN;

or this

int64_t a = std::numeric_limits<int64_t>::min();
like image 9
john Avatar answered Oct 10 '22 19:10

john