简体   繁体   中英

How to shorten declaring named constants?

So if I had to declare multiple constants of the same type like the example below, is there a way to increase efficiency while cutting down the length of the code? This is for C++.

const double DISCOUNT = .2;

const double CUT_OFF = 150;

const double SHIP_CHARGE = 8.5;

const double TAX_RATE = 0.0825;

Well, you can write it like the following, but really there's no reason to:

const double DISCOUNT = .2, CUT_OFF = 150, SHIP_CHARGE = 8.5, TAX_RATE = 0.0825;

It's debatable whether it's more readable or not. I personally don't recommend it, and the C++ Core Guidelines don't recommend it either .

As a side note, you should be using constexpr instead of const for things like this.

Well,

#define A(b, c) const double b = c;
A(DISCOUNT, .2)
A(CUT_OFF, 150)
A(SHIP_CHARGE, 8.5)
A(TAX_RATE, .0825)

has fewer characters. But it's very hard to read indeed. From C++11 onwards prefer constexpr to const .

"Golfing" C++ code is never to be recommended. Write clear code.

Well, this is the way I would do it...

Instead ot T you my use something else.

using T = const double;

T DISCOUNT = .2;
T CUT_OFF = 150;
T SHIP_CHARGE = 8.5;
T TAX_RATE = 0.0825;

I also would use constexpr but in this case const is the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM