Is there a more human-readable way for representing big numbers in the source code of an application written in C++ or C?
let's for example take the number 2,345,879,444,641
, in C or C++ if we wanted a program to return this number we would do return 2345879444641
.
But this is not really readable.
In PAWN (a scripting language) for example I can do return 2_345_879_444_641
or even return 2_34_58_79_44_46_41
and these both would return the number 2,345,879,444,641
.
This is much more readable for the human-eye.
Is there a C or C++ equivalent for this?
With a current compiler (C++14 or newer), you can use apostrophes, like:
auto a = 1'234'567;
If you're still stuck with C++11, you could use a user-defined literal to support something like: int i = "1_000_000"_i
. The code would look something like this:
#include <iostream>
#include <string>
#include <cstdlib>
int operator "" _i (char const *in, size_t len) {
std::string input(in, len);
int pos;
while (std::string::npos != (pos=input.find_first_of("_,")))
input.erase(pos, 1);
return std::strtol(input.c_str(), NULL, 10);
}
int main() {
std::cout << "1_000_000_000"_i;
}
As I've written it, this supports underscores or commas interchangeably, so you could use one or the other, or both. For example, "1,000_000" would turn out as 1000000
.
Of course, Europeans would probably prefer "." instead of "," -- if so, feel free to modify as you see fit.
With Boost.PP:
#define NUM(...) \
NUM_SEQ(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))
#define NUM_SEQ(seq) \
BOOST_PP_SEQ_FOLD_LEFT(NUM_FOLD, BOOST_PP_SEQ_HEAD(seq), BOOST_PP_SEQ_TAIL(seq))
#define NUM_FOLD(_, acc, x) \
BOOST_PP_CAT(acc, x)
Usage:
NUM(123, 456, 789) // Expands to 123456789
Demo.
Another way is making an UDL. Left as an exercise (and also because it requires more code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With