On 17/01/2023 14:52, Paul N wrote:
> On Tuesday, January 17, 2023 at 1:23:47 PM UTC, Öö Tiib wrote:
>> On Tuesday, 17 January 2023 at 14:29:51 UTC+2, Paul N wrote:
>>> I'm attempting to write a Bridge program, and it's getting quite messy.
>>>
>>> At first I simply used a number for each bid, so my code had a lot of "magic numbers" in it. I got rid of some by using an enum, as follows:
>>>
>>> enum { B_PASS = 0, B_DOUBLE = 1, B_REDOUBLE = 2,
>>> B_1C = 15, B_1D = 18, B_1H = 21, B_1S = 24, B_1NT = 27,
>>> B_2C = 30, B_2D = 33, B_2H = 36, B_2S = 39, B_2NT = 42,
>>> B_3C = 45, B_3D = 48, B_3H = 51, B_3S = 54, B_3NT = 57,
>>> B_4C = 60, B_4D = 63, B_4H = 66, B_4S = 69, B_4NT = 72 };
>>>
>> Nameless type, SCREAMING CAPS names and then using just ints anyway?
>
> Well, it's nearly a macro, isn't it? If you have any better ideas,
> I'd (seriously) be glad to hear them, that's the whole point of this
> post.
>
Macro names don't need all caps. I only ever use all-caps names if I
have a macro that is doing something weird, and you have to pay special
attention to it. So if I have a function-like macro that behaves very
much like a function, it does not need all-caps in the name. (Of
course, in C++ this generally would be a real function - it's more
common in C, when you need something that is type generic and you don't
have templates.) Similarly, macros that are simple constants do not
need all-caps names. (And again, there are usually better choices than
macros.)
If the macro evaluates a parameter more than once, or plays silly
buggers with scopes, declares new variables, etc., in a way that is not
obvious in its use, then all-caps is a good warning. But overuse of a
warning negates its effectiveness.
> The values aren't random, they also represent contracts, with 16
> representing 1 clubs doubled, 17 representing 1 clubs redoubled,
> etc.
>
Then don't define them this way. Do it using a constexpr function, as
discussed in other posts, or by some completely different arrangement
(such as a const template variable, or a class that wraps the value
while storing it in a bitfield struct - there are a number of options).
Whenever there are hand-calculated magic numbers, you should be
sceptical. It /might/ be the simplest and clearest way to write the
code, but it might not be. And it's seldom the most /fun/ way to write
the code!