You can create a mask based on doSet
value:
#define AMAZING_FLAG_IDX 1#define AMAZING_FLAG (1u << AMAZING_FLAG_IDX)...uint16_t set_mask = doSet << AMAZING_FLAG_IDX;
Now your check can look like this:
setAmazingFlag(bool doSet){ const uint16_t set_mask = doSet << AMAZING_FLAG_IDX; if (flags & set_mask) { // Really expensive thing // Update flags }}
On some architectures, !!
may be compiled to a branch and by this, you may have two branches:
- Normalisation by
!!(expr)
- Compare to
doSet
The advantage of my proposal is a guaranteed single branch.
Note: make sure you don't introduce undefined behaviour by shifting left by more than 30 (assuming integer is 32 bits). This can be easily achieved by a static_assert(AMAZING_FLAG_IDX < sizeof(int)*CHAR_BIT-1, "Invalid AMAZING_FLAG_IDX");