user542687
user542687

Reputation:

Defining names in place of "true" and "false" for bool type

I am wanting to use a bool to switch back and forth between loading X and loading Y from a file. I don't want to use "true" and "false", because it doesn't make the code clear. I would rather use something like LOAD_X or LOAD_Y... Is the following code the way to do it? Or is there a better way?

#define LOAD_X true
#define LOAD_Y false

Edit: Okay, so it seems an enum is the way to go... but what should the naming scheme be? Like all caps, or lower case for the first word, uppercase for following words, etc.

Upvotes: 2

Views: 8084

Answers (4)

luckywong
luckywong

Reputation: 1

i think Load X IS LOAD. Lowercase font look more friendly, you can choose bright colors. enum LoadType { LoadY, LoadX it is all right.

Upvotes: -1

Lou Franco
Lou Franco

Reputation: 89232

I would use an enum instead. Just because there are two choices, doesn't mean the type should be bool

enum load_type { loadX, loadY };

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

I guess that works, if you'll only ever have two options. I'd be tempted to go for an enum:

enum LOADMODE {
    LOAD_X,
    LOAD_Y
};

At the very least, prefer constants over macros:

const bool LOAD_X = true;
const bool LOAD_Y = false;

They will abide by scope rules and won't silently break stuff without you realising when names conflict.

Upvotes: 3

James McNellis
James McNellis

Reputation: 355207

You can use an enum:

enum LoadType {
    LoadY,
    LoadX
};

Or, you might prefer to constrain the scope of the enumerators by using a namespace:

namespace LoadType {
    enum Type {
        LoadY,
        LoadX
    };
};

The advantage of using an enum is that if your function takes a LoadType (or a LoadType::Type in the second example), you can't pass it any arbitrary integer or bool; you can only pass it one of the enumerators (or something explicitly cast to the enumeration type, which is really easy to spot in a code review).

Upvotes: 7

Related Questions