Can I multiply an int by boolean in C ++?

I have a widget in my GUI that displays charts. If I have more than one chart, the chart will display the legend shown in the rectangle.

I have a QStringlist (legendText) that contains the legend text. If there is no legend, legendText will be empty. If there is a legend, legendText will contain the text.

To find the height of the rectangle around the legend, I would like to do the following:

  int height = 10; QStringList legendText; ... height = height * (legendText->size() > 0); ... 

Is it a good idea / good style to multiply int by boolean ? Will I have problems with this?

+50
c ++ int boolean
Oct 15 '15 at 7:14
source share
5 answers

This is technically good if a little unclear.

bool will advance to int , so the result will be determined. However, looking at this code, I do not immediately get the semantics that you are trying to achieve.

I would just write something like:

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

It makes your intention more clear.

+107
Oct. 15 '15 at 7:20
source share

This is excellent according to the standard (Β§4.5 / 6):

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

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

Or use a conditional statement as other answers indicate (but still with isEmpty instead of .size() > 0 )

+32
Oct. 15 '15 at 7:18
source share

You can use the conditional (triple) operator:

 height = ( legendText->size() >0 ) ? height : 0 ; 
+16
Oct. 15 '15 at 7:19
source share

Maybe this?

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

or

 int height = legendText->isEmpty() ? 0 : 10; 
+11
Oct. 15 '15 at 9:20
source share

Some people may find the following useful information (the following code should be considered in high-performance programs, where each synchronization cycle matters, and the goal here is to show alternative methods, I would not use it in this particular situation).

If you need fast code without branches, you can implement int multiplication with boolean using bitwise operators.

 bool b = true; int number = 10; number = b*number; 

can be optimized for:

 number = (-b & number); 

If b is true , then -b is -1 , and all bits are set to 1 . Otherwise, all bits are 0 .
Boolean NOT ( !b ) can be implemented with XOR'ing b with 1 ( b^1 ).
Therefore, in your case, we get the following expression:

 height = (-(legendText->isEmpty()^1) & height); 
0
Oct 23 '15 at 23:42
source share



All Articles