Reputation: 6584
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.)
Upvotes: 10
Views: 10957
Reputation: 140267
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.
Upvotes: 24
Reputation: 75389
C defines 0 as false and everything else as true. Positive, negative, whatever.
I believe I recently advocated the use of typedef enum { false, true } bool;
so I'll own up to it. (If my original code didn't have a typedef
involved, that was an error of judgement on my part.) All nonzero values are true, so I wouldn't advocate using an enumerated bool
type for things like this:
if(x == true) // not what you want
if(!x == false) // works, but why so much effort?
I generally perfer simply if(x)
or if(!x)
to explicit tests against boolean values. However, sometimes it's good to have a boolean type:
bool is_something(int x)
{ // assume for the sake of an argument that the test is reasonably complex
if(/* something */) return false;
if(/* something else */) return true;
return false;
}
This is no better than having the type be int
, but at least you're being explicit with what the result is meant for.
Also, as per someone else above, a better bool
might be:
typedef enum { false, true = !false } bool;
I believe !
is guaranteed to return 0 or 1, but I could be wrong, and the above works well either way.
Upvotes: -1
Reputation: 10317
This is the correct behavior, in C 0 is False and everything else is True
Upvotes: 2
Reputation: 6532
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.
Upvotes: 2
Reputation: 20721
In C, there is no boolean type; 0 and 0.0f are considered "false" in boolean contexts, everything else is "true".
Declaring "true" and "false" in an enum is wrong, because then the following code will break:
if (2 == TRUE)
(2 should evaluate as "true", but if TRUE has been defined as 1, the two values aren't considered equal).
Upvotes: 1