if(10)
it is true, but if(10 == true)
is false. Can someone tell me why the first case convert the number to bool but the second case didnt?
To sum up: To check if a variable is equal to True/False (and you don't have to distinguish between True / False and truthy / falsy values), use if variable or if not variable . It's the simplest and fastest way to do this.
You can check if a value is either truthy or falsy with the built-in bool() function. According to the Python Documentation, this function: Returns a Boolean value, i.e. one of True or False .
An alternative approach is to use the logical OR (||) operator. To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean.
We can evaluate values and variables using the Python bool() function. This method is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.
if (10)
is equivalent to if (10 != 0)
, whereas if (10 == true)
is if (10 == 1)
(since true
is promoted to the value 1
of type int
).
In layman's terms: Two things that both happen to satisfy some property aren't automatically the same thing.
(E.g. doughnuts and frisbees are both round, but that doesn't mean a doughnut is equal to a frisbee. Integers and booleans can both be evaluated in a boolean context, but that doesn't mean that every integer that evaluates as true is equal to every true boolean.)
if( ... )
{
// if statement
}
To execute if
statement in C++, ...
should have a true
value.
When you wrote if( 10 ){//something useful}
I think 10
treats as int
but not bool
variable. The following logic should be applied then
if( 10 ) -> if( bool( 10 ) ) -> if( true )
When you write if( 10 == true ){//something useful}
, according to C++ standard, there should be the following logic behind the scene
if( 10 == true ) -> if( 10 == int( true ) ) -> if( 10 == 1 ) -> if( false )
You may write something like
if( 10 != false )
or
if( !!10 == true )
also
if( ( bool ) 10 == true ) // alternatively, if( bool ( 10 ) == true )
In old C
(before C99
), there is no false
or true
, but there are 0 or non-0 values.
In modern C
(from C99
), there is false
or true
(<stdbool.h>
), but they are syntactic sugar for 0
and 1
, respectively.
if( 10 ) // evaluates directly since 10 is non-zero value
if( 10 == true ) -> if( 10 == 1 ) -> if( 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