1

I've come across this a few times recently:

if ((flags & PERFORM_DELETION_CONCURRENTLY) == PERFORM_DELETION_CONCURRENTLY)
   ...

What's the reason for the extra comparison? Why not this?

if (flags & PERFORM_DELETION_CONCURRENTLY)
   ...

My guess is that it's a leftover habit to silence warnings from the days of yore when compilers were more strict.

1
  • 1
    "when compilers were more strict" where do you get such idea from? Merely the reverse is true, the C language and compilers with it get more stricter. Sep 24, 2012 at 11:45

2 Answers 2

6

There is also the possibility that in the mask there is more than one bit set. In that case, the two comparisons have different semantics.

8
  • Yep, occurred to me seconds after I posted the question. Thanks.
    – Max
    Sep 24, 2012 at 11:20
  • 1
    To be precise, it is true iff all of the bits in PERFORM_DELETION_CONCURRENTLY are set in flags. A slightly more efficient way to do this is if ((~flags & PERFORM_DELETION_CONCURRENTLY) == 0) ... which I bury in an ALL_BITS_SET macro in my standard header file, which makes the code more readable/understandable as well.
    – Jim Balter
    Sep 24, 2012 at 11:23
  • @JimBalter definitely agree to being faster, at the cost of being less readable in my opinion. One has to do some extra mental translation to understand what it is doing.
    – fkl
    Sep 24, 2012 at 11:25
  • @fayyazkl Wrong, it is more readable because I bury it in a macro with a meaningful name. Very few programmers (myself being one) readily grasp what if ((x & y) == y) does, so that isn't understandable at all.
    – Jim Balter
    Sep 24, 2012 at 11:29
  • @JimBalter Agree to the part of more readable macro name without showing implementation. Perhaps it is a difference of personal traits or what being used to of. I feel like naturally reading the above if (x&y == y) in a go. But have to put significant effort with the one with ~ and comparison with 0. I wonder if this is common with other people. Just my opinion
    – fkl
    Sep 24, 2012 at 11:33
2

To be precise, the condition is true iff all of the bits in PERFORM_DELETION_CONCURRENTLY are set in flags. A slightly more efficient way (on some architectures) to do this is if ((~flags & PERFORM_DELETION_CONCURRENTLY) == 0) ... which I bury in an ALL_BITS_SET macro in my standard header file, which makes the code more readable/understandable as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.