Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does casting an int to a bool give a warning?

Shouldn't it be ok to use static_cast to convert int to bool as it converts reverse of implicit conversion but i still get a warning?

Example:

MSVC++ 8

bool bit = static_cast<bool>(100);
like image 265
user4344 Avatar asked Feb 11 '11 10:02

user4344


People also ask

How do I assign an int to a boolean?

While declaration, we will initialize it with the val value comparing it with an integer using the == operator. If the value matches, the value “True” is returned, else “False” is returned. boolean bool = (val == 100); Let us now see the complete example displaying how to convert integer to boolean.

Can you add a bool to an int?

Yes, you can cast from int to bool and back. If you cast from bool to int, the result will be 0 (false) or 1 (true). If you cast from int to bool, the result will be false (0) or true (any value other than zero).

Is bool the same as int?

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

Just because the conversion a => b is implicit doesn’t say anything about the viability of the reverse, b => a.

In your case, you shouldn’t cast at all. Just do the obvious thing: compare:

bool result = int_value != 0;

This is the only logically correct way of converting an int to bool and it makes the code much more readable (because it makes the assumptions explicit).

The same applies for the reverse, by the way. Converting implicitly from bool to int is just lazy. Make the mapping explicit:

int result = condition ? 1 : 0;
like image 58
Konrad Rudolph Avatar answered Sep 27 '22 18:09

Konrad Rudolph