joe_04_04 joe_04_04 - 3 months ago 6
C++ Question

Any way to format large numbers in code to make easier to read?

I've done a bit of searching for a solution to this (or a previously asked question on SO), but all that turns up are results for formatting numbers in the output of a program, which is not what I'm looking for. My question is, are there any solutions to formatting large numbers IN code (not the output of a program) to make them easier to read.

For instance

int main()
{
int LargeNumber = 1000000;
}


This number holds 1 million, but its not so easy to tell right away without moving the cursor over it and counting. Are there any good solutions to this besides using a comment?

int main()
{
int LargeNumber = 1000000;//1,000,000
}


Thank you.

Answer

The current standard allows you to insert apostrophes as separators in literals, so your code would look like:

int main()
{
    int LargeNumber = 1'000'000;
}

This was added relatively recently (in C++14), however, so if you're using an older compiler, it may not be supported yet. Depending on the compiler, you may also need to add a flag to ask for conformance with the most recent standard to get the compiler to accept this. Offhand I don't remember the exact compiler versions necessary to support it, but it works with the current versions of the major compilers (e.g., g++, clang, and VC++).

Comments