Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

format

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.

like image 483
joe_04_04 Avatar asked Aug 17 '16 03:08

joe_04_04


1 Answers

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++).

like image 134
Jerry Coffin Avatar answered Sep 27 '22 21:09

Jerry Coffin