Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Should I use INT64_C as "int64_t literal" …?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading