Representing big numbers in source code for readability?

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.

Leave a Comment