In C, at least every positive value except for 0 is treated as a boolean true. But what about a negative value? I did some tests and it seems that also negative values are treated as a boolean true. Is this a defined behaviour or implementation specific?
(I came to think about this when I saw in a question, someone promoting declaring "true" and "false" in an enum as 1 and 0.)
They make code harder to read. A negative variable name holds a boolean that tells of whether we should not do something. In imperative code they're usually evaluated in conditional expressions in logical statements, like if and while . do_not_do_it tells whether we shouldn't do it.
All non-zero values will be converted to true , and zero values to false . With negative numbers being non-zero, they are converted to true .
Boolean variables are displayed as either True or False. Like C, when other numeric data types are converted to Boolean values then a 0 becomes False and any other values become True. When Boolean values are converted to other data types, False becomes 0 while True becomes –1.
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. Copied!
This is defined behavior. I'll look for the C99 standard paragraph stating as such
§ 6.3.1.2
When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
I believe 0 is false and everything else is true.
See @casper's reply here: thread
I would take a hint from C here, where false is defined absolutely as 0, and true is defined as not false. This is an important distinction, when compared to an absolute value for true. Unless you have a type that only has two states, you have to account for all values within that value type, what is true, and what is false.
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