(Question is related to my previous questions here, here, here, and here).
I am maintaining a very old application that was ported years ago from DOS to Windows, but a lot of the old C conventions still carry forward.
The one particular convention is a setBit and clrBit macro:
#ifndef setBit
#define setBit(word, mask) word |= mask
#endif
#ifndef clrBit
#define clrBit(word, mask) word &= ~mask
#endif
I found that I could declare a variable as an enum type and set my variable equal to the one of the enumerated values that are defined.
enum SystemStatus
{
SYSTEM_ONLINE = BIT0,
SYSTEM_STATUS2 = BIT1,
SYSTEM_STATUS3 = BIT2,
SYSTEM_STATUS4 = BIT3
};
With BIT0 = 0x00000001, BIT1 = 0x00000002, etc.
SystemStatus systemStatus;
systemStatus = SYSTEM_ONLINE
In your opinion, is using the setBit and clrBit macros more C like or C++ like – and would it be better to simply declare variables as an enumerated type and get rid of all the old setBit/clrBit stuff?
I think you’re confusing the purposes. The enum is about setting up values to use as flags. setBit and clrBit are about operating on data. That data might happen to be a flag, but that’s really the only relationship between the two ideas.
That being said, macros are certainly NOT the C++ way of doing things. You would use inline functions instead. For example:
Edit to fend off nitpickers:
This is just an example of how you could implement the functions. You don’t need to use templates, you can use two template parameters instead of 1, you can use a void function or values instead of references if you want, (though then it would lose some of the original semantics). The main point is to get the benefits of type safety which you won’t find in macros (among many other downsides of macros). http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.5
Edit: Here’s a void, non-template version for comparison