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

2

12

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?

Coughlin answered 19/7, 2019 at 4:18 Comment(0)
O
20

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.

Osprey answered 19/7, 2019 at 4:22 Comment(0)
N
9

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();
Neese answered 19/7, 2019 at 4:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.