Can I multiply an int with a boolean in C++?

Solution 1:

This is technically fine, if a bit unclear.

The bool will be promoted to an int, so the result is well-defined. However, looking at that code I don't instantly get the semantics you are trying to achieve.

I would simply write something like:

height = legendText->isEmpty() ? 0 : height;

This makes your intent far clearer.

Solution 2:

It's perfectly fine according to the standard (§4.5/6):

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

However, I suggest using isEmpty instead of comparing size to zero height = height * (!legendText->isEmpty());

Or use the conditional operator as the other answers suggest (but still with isEmpty instead of .size() > 0)

Solution 3:

You can use the conditional (ternary) operator:

height = ( legendText->size() >0 ) ? height : 0 ;

Solution 4:

Maybe this?

if(legendText->isEmpty())
{
   height = 0;
}

or

int height = legendText->isEmpty() ? 0 : 10;