SchnJulian
SchnJulian

Reputation: 192

Are constant "flags" considered good style? (c++)

I am currently working an a library and I wonder if it's considered good style to have all-caps constants like:

constexpr int ONLY_LOWERCASE = 1;
constexpr int ONLY_UPPERCASE = 2;

And so on. I plan on using it to let the library user control the behavior of the functions like:

doSomeThing(var, ONLY_UPPERCASE);+

Thanks

Upvotes: 1

Views: 301

Answers (1)

Coral Kashri
Coral Kashri

Reputation: 3506

It's seems like you are using integer structure to store boolean data. It might considered as a better way to use boolean structure for this purpose, for memory usage reasons.

One way of archive this target is using enum or enum class that inherit from bool:

enum class string_case : bool {
    ONLY_LOWERCASE,
    ONLY_UPPERCASE
}

This way you will use a single byte that indicate whatever you want, instead of 8 bytes in your example.

Usage example:

doSomeThing(var, string_case::ONLY_UPPERCASE);

Edit

In case you have more than 2 flags, you can still use enum (just without inheritance from bool):

enum class string_case {
    ONLY_LOWERCASE = 1,
    ONLY_UPPERCASE = 2,
    FLAG_3 = 3,
    FLAG_4 = 4
};

And even so, using only 4 bytes (instead of 4(bytes) * flags_count).
Another approach, if multiple flags can be on together (and you don't want to play with bits in your enum calculations), you can use a struct:

struct options {
    bool option_1: 1;
    bool option_2: 1;
    bool option_3: 1;
    bool option_4: 1;
};

And in this way you'll only use the amount of bytes that you need to store those bits.

Upvotes: 2

Related Questions