Imagine there are two flags in the program that are independent of each other. We might implement macros to manipulate them as shown in the code sample below. It would probably be wise to put the macros in a header file.
// the flag definitions
#define CAR_LOCKED 0x01 // 0000 0001
#define CAR_PARKED 0x02 // 0000 0010
#define CAR_RESET 0x00 // 0000 0000
// macros to manipulate the flags
#define RESET_CAR(x) (x = CAR_RESET)
#define SET_LOCKED(x) (x |= CAR_LOCKED)
#define SET_PARKED(x) (x |= CAR_PARKED)
#define UNSET_LOCKED(x) (x &= (~CAR_LOCKED))
#define UNSET_PARKED(x) (x &= (~CAR_PARKED))
#define TOGGLE_LOCKED(x) (x ^= CAR_LOCKED)
#define TOGGLE_PARKED(x) (x ^= CAR_PARKED)
// these evaluate to non-zero if the flag is set
#define IS_LOCKED(x) (x & CAR_LOCKED)
#define IS_PARKED(x) (x & CAR_PARKED)
// a short program that demonstrates how to use the macros
int
main(void)
{
unsigned char fMercedes, fCivic;
RESET_CAR(fMercedes);
RESET_CAR(fCivic);
SET_LOCKED(fMercedes);
if( IS_LOCKED(fMercedes) != 0 )
{
UNSET_PARKED(fCivic);
}
TOGGLE_LOCKED(fMercedes);
return 0;
}
No comments:
Post a Comment