Quantcast
Channel: User Alex Lop. - Stack Overflow
Viewing all articles
Browse latest Browse all 39

Answer by Alex Lop. for Comparing a bit to a boolean

$
0
0

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:

  1. Normalisation by !!(expr)
  2. 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");


Viewing all articles
Browse latest Browse all 39

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>