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

微笑、不失礼 提交于 2019-12-01 02:03:13

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:

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.

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

Another idea could be:

#define _000 *1000

int k = 1 _000 _000;

As this reminds me of digit grouping my first clumsy approach without C++14
would be

#define INTGROUPED1(a)     (a%1000)
#define INTGROUPED2(a,b)   (a%1000*1000 + b%1000)
#define INTGROUPED3(a,b,c) (a%1000*1000000 + b%1000*1000 + c%1000)
int v1 = INTGROUPED1(        123);
int v2 = INTGROUPED2(    123,123);
int v3 = INTGROUPED3( 23,123,123);

but I would use such tricks rather in a private context.

Just consider someone writing

INTGROUPED3(1234,1234,1234); //This would be (234,234,234) without a compiler complaining

EDIT1:

Maybe a better aproach would be using the ## preprocessor operator

#define NUM_GROUPED_4ARGS(a,b,c,d) (##a##b##c##d)
int num = NUM_GROUPED_4ARGS(-2,123,456,789); //int num = (-2123456789);

This is more like WYSIWYG but not immune against misuse. E. g. you might wnat the compiler to complain about

int num = NUM_GROUPED_4ARGS(-2,/123,456,789);  //int num = (-2/123456789); 

but it will not.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!