Just wondering if it's better style/more efficient to write code like this:
if (bitset[index] & 1)
{
//do something
}
vs:
if (bitset[index] == 1)
{
//do something
}
Thanks!
None of the above. From the comments, you are talking about something like C++'s std::bitset
, whose operator[]
returns bool
. Normally, boolean values are only operated together with other boolean values, using boolean operations (&&
, ||
, !
, etc). It seems strange to compare it with an object of another type (e.g. the integer 1), or to apply integer arithmetic operations like & | + -
etc. The conversion rules of the language let you do it, but it doesn't make as much logical sense.
So the most idiomatic, and also most compact, version would be:
if (bitset[index]) {
// ...
}
If it makes more sense in context to think of the test as an equality comparison, then you can:
if (bitset[index] == true) {
// ...
}
but to most C++ programmers this would simply look redundant.
This is all irrelevant from the standpoint of optimization; any reasonable compiler will realize that they are all equivalent and optimize them all the same. In general, though, if you're doing something common, then you will usually get the best optimization by writing it in the most common and idiomatic way, as that is what the compiler is most likely to handle well.