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);
- Fails to compile on MacOS when I use
1L
as the constant value. - Using
1LL
also fails to compile on Ubuntu 20.04.
I found INT64_C as a potential solution, but the documentation is unclear.
2
Answers
Replacing
1
byINT64_C(1)
is likely to "work", but it’s not guaranteed. TheINT64_C
macro expands to an expression of typeint_least64_t
. That’s likely to be the same type asint64_t
, but it’s not guaranteed. For example, iflong
andlong long
are both 64 bits, it’s possible thatint_least64_t
could belong
andint64_t
could belong 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 anint64_t
value, since it will likely be promoted. Arguments tostd::min
are an exception; you need an expression that’s actually of typeint64_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:Or you can define a constant of the right type and use that instead of the literal:
The first answer provided quite exotic solutions. What you need is just setting the parameters type: