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
1Las the constant value. - Using
1LLalso fails to compile on Ubuntu 20.04.
I found INT64_C as a potential solution, but the documentation is unclear.
Replacing
1byINT64_C(1)is likely to "work", but it's not guaranteed. TheINT64_Cmacro 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, iflongandlong longare both 64 bits, it's possible thatint_least64_tcould belongandint64_tcould 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_tis usable in a context where you need anint64_tvalue, since it will likely be promoted. Arguments tostd::minare 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: