Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are negative boolean values defined?

Tags:

c

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.)

like image 441
onemasse Avatar asked Nov 23 '10 09:11

onemasse


People also ask

Can a Boolean variable be negative?

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.

Are negative numbers considered true or false?

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 .

How do you define a Boolean variable?

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.

How do you know if a Boolean value is true?

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!


2 Answers

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.

like image 157
SiegeX Avatar answered Oct 20 '22 15:10

SiegeX


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.

like image 36
posdef Avatar answered Oct 20 '22 16:10

posdef