Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to write a large number in C++ source code with spaces to make it more readable? [duplicate]

Try digit separator:

int i = 1'000'000'000;

This feature is introduced since C++14. It uses single quote (') as digit separator.


Also see:

  • Why was the space character not chosen for C++14 digit separators?
  • Generalizing Overloading for C++2000 (April's joke by the father of C++ himself)

When I've done similar things on platforms without C++14 (generally for microprocessors), I've represented large numbers by splitting it up with multiplication:

int i = (1000 * 1000 * 1000);

Add UL or L postfixes to taste

The advantage here is that it's compliant to basically any platform that supports C89 (and probably earlier).

Generally, it's probably safe to assume the multiplication operators will fall out at compile time, but if you're using constants like this in a loop, it might be worth double-checking.


I usually #define constants for this purpose, as it saves counting zeroes and makes it very clear what you mean to anyone viewing the code. For example

#define THOUSAND 1000
#define MILLION 1000000

vector<int> temp = vector<int>(THOUSAND * MILLION);

This makes it clear I really do mean a thousand million and did not miscount the zeros

Obviously you can use enums if you prefer.


Another idea could be:

#define _000 *1000

int k = 1 _000 _000;

If you don't use C++14, another option would be using some kind of string-inherited class with an implicit int-cast and maybe a regex-check in the constructor to restrict the numbers. I use CString for an easy example.

class NumString : public CString
{
public:
    NumString(CString number) : num(number) { } //maybe insert some regex-check here
    operator long() const
    {
        CString tmp = num;
        tmp.Remove(' ');        
        return atol(tmp);
    }
private:
    CString num;
};


NumString a = "1 000 000 000";
int b = a;
bool test = b == 1000000000;
//test will be true