How can I write portable code to compare a constant integer value with an int64_t variable across different platforms (MacOS and Ubuntu)?
int64_t a = 2;
std::min(1, a);
1L
as the constant value.1LL
also fails to compile on Ubuntu 20.04.I found INT64_C as a potential solution, but the documentation is unclear.
int64_t a = 2;
std::min(1, a); // error (unless int64_t is int)
Replacing 1
by INT64_C(1)
is likely to "work", but it's not guaranteed. The INT64_C
macro expands to an expression of type int_least64_t
. That's likely to be the same type as int64_t
, but it's not guaranteed. For example, if long
and long long
are both 64 bits, it's possible that int_least64_t
could be long
and int64_t
could be long long
. There's not much reason for an implementation to define them differently, but you shouldn't rely on that.
It's defined that way because, in most contexts, a constant of type int_least64_t
is usable in a context where you need an int64_t
value, since it will likely be promoted. Arguments to std::min
are an exception; you need an expression that's actually of type int64_t
.
There is no syntax for defining a literal of type int64_t
. But you can have a constant expression of that type by using a conversion:
int64_t a = 2;
std::min(int64_t(1), a);
Or you can define a constant of the right type and use that instead of the literal:
std::int64_t a = 2;
constexpr int64_t one = 1;
std::min(one, a);