Pointer
Pointer

Reputation: 65

Add bool variable to int

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

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

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

cigien
cigien

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

Related Questions