Enum vs Macro States C ++

(The question is related to my previous questions here , here , here , and here ).

I support a very old application, ported a few years ago from DOS to Windows, but many old C conventions are still ported.

The only specific convention is the macro setBit and clrBit:

#ifndef setBit
#define setBit(word, mask) word |= mask
#endif

#ifndef clrBit
#define clrBit(word, mask) word &= ~mask
#endif

I found that I can declare a variable as an enumeration type and set my variable equal to one of the enumerated values ​​listed.

enum SystemStatus
{
    SYSTEM_ONLINE                = BIT0,
    SYSTEM_STATUS2               = BIT1,
    SYSTEM_STATUS3               = BIT2,
    SYSTEM_STATUS4               = BIT3
};

C BIT0 = 0x00000001, BIT1 = 0x00000002etc.

SystemStatus systemStatus;

systemStatus = SYSTEM_ONLINE

In your opinion, uses the setBit and clrBit macros more like C or C ++ - and would it be better to just declare the variables as an enumerated type and get rid of all the old setBit / clrBit stuff?

+3
6

, . - . setBit clrBit . , .

, , , ++- . . :

template<typename T>
inline T& setBit(T& word, T mask) { return word |= mask; }

template<typename T>
inline T& clrBit(T& word, T mask) { return word &= ~mask; }

, nitpickers:

, . , 1, void , , ( ). - , ( ). http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.5

: void,

inline void setBit(unsigned int word, unsigned int mask) { word |= mask; }

inline void clrBit(unsigned int word, unsigned int mask) { word &= ~mask; }
+4

, - enum , . BIT0, BIT1 .? INT0, INT1 .. - .

, C-, - ? , - , .

+7

setBit clrBit , ++. , , :

  SystemStatus systemStatus = SYSTEM_ONLINE | SYSTEM_STATUS3;

- .

systemStatus = clrBit(systemStatus, SYSTEM_STATUS3);
systemStatus = setBit(systemStatus, SYSTEM_STATUS4);
+6

, - , , , . . 0101, .

, ,

systemStatus = SYSTEM_ONLINE | BIT2;

, , .

+2

enum, , , , . , . #define ( enum, ) , , , set/clear.

C. () enum " ++". ++- . + -, setBit clrBit, . , systemStatus -= SYSTEM_ONLINE ( #define SYSTEM_ONLINE (1<<31) ), "System Online", . STL Bitset .

: , BIT0 .. - , .

+1
source

I agree with bta strong> if you want to use the C ++ approach, you should create a class that abstracts the entire implementation about the states.

But I will not overload the operators + =, - =, because you continue to wear the old school.

I suggest a method declaration for this.

You can choose one method with a boolean flag or two for tuning and cleaning.

class Status{...};

void main(){
    Status status;

    //first approach
    status.SystemOnline(true);
    status.BackUPOnline(false);

    //second approach
    status.SetEmergencySystem();
    status.ClearSystemOnline();
}

with this style, you encapsulate an implementation on how to implement information storage.

+1
source

Source: https://habr.com/ru/post/1754478/


All Articles