Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

int

boolean

I have a widget in my GUI that displays chart(s). If I have more than one chart there will be a legend shown in a rectangle on the GUI.

I have a QStringlist (legendText) which holds the text of the legend. If there is no legend required, legendText would be empty. If there will be a legend, legendText would hold the text.

For finding 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 this a good idea/ good style to multiply an int with a boolean? Will I run into problems with that?

like image 339
user3443063 Avatar asked Oct 15 '15 07:10

user3443063


People also ask

Can you multiply boolean in C?

Yes. It's safe to assume true is 1 and false is 0 when used in expressions as you do and is guaranteed: C++11, Integral Promotions, 4.5: An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.

Can we multiply int and float in C?

The result of the multiplication of a float and an int is a float . Besides that, it will get promoted to double when passing to printf .

Can boolean be stored in int?

Nope, bools are designed to only store a 1 or a 0.

Can int be true or false?

Treating integers as boolean values C++ does not really have a boolean type; bool is the same as int. Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true.


1 Answers

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.

like image 127
TartanLlama Avatar answered Sep 29 '22 01:09

TartanLlama