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);
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.
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).
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With