Reputation: 65
I have in my code a boolean function "lookup" which has the parameter byte: lookup(byte). My variable _size is an integer. Is it good practice to do stuff like following:
_size += !lookup(byte);
I mean the point is the implicit cast from bool and int. Otherwise I have to do something like this
if (!lookup(byte)) {
_size++;
}
but I thought that would be less efficient.
Upvotes: 0
Views: 250
Reputation: 122486
There is no difference in efficiency. Compilers apply optimizations and the outcome of both is likely exactly the same.
If you want to make the conversion more explicit you could use a static_cast
:
_size += static_cast<size_t>(!lookup(byte));
Upvotes: 1
Reputation: 60228
The expression !lookup(byte)
is guaranteed to have one of the values, true
or false
. When used as an int
, these are converted to 1
and 0
respectively.
So the following 2 snippets:
_size += !lookup(byte); // true -> add 1, false -> add 0
and
if (!lookup(byte)) { // if true
_size++; // add 1
}
are equivalent. You should pick whichever one is easier to read, and understand. The compiler is going to generate the same assembly for both versions, so you don't have to worry about efficiency.
Upvotes: 3