enum bool{true,false};
void main()
{
if(true==(2==3))
{
printf("true\n");
}
else
{
printf("false\n");
}
return 0;
}
views:
286answers:
5The enum true is 0 in this case.
so:
0==(2==3)
0==(0)
1
1 is true. Thus this conditional is always true.
It's because the default starting point for enum
s in C
is 0, which happens to be false, not true.
You should use enum bool {false, true}
instead. And please don't use abominations like
if (x == true)
if (x == false)
at all. You'd be better off with
if (x)
if (!x)
By all means, use true
and false
for setting booleans but you should never have to test them that way. Especially since the definition is zero/non-zero, not zero/one.
I've always liked (if you really have to):
#define false (1==0)
#define true (1==1)
That's at least guaranteed to work.
In your enumeration, true
has the constant value 0, and false
has the constant value 1.
In C, the result of an equality comparison (2==3) is either 0 for not equal, or 1 for equal. Your code is:
if ( 0 == (2==3) )
or
if ( 0 == 0 )
Which is clearly true.
Defining the enums 'true' and 'false' is a bad idea anyway. In C, 'false' is zero, and 'true' is non-zero... true is not necessarily '1'.