tags:

views:

286

answers:

5
enum bool{true,false};
void main()
{
    if(true==(2==3))
    {
        printf("true\n");
    }
    else
    {
        printf("false\n");
    }

    return 0;
}
+12  A: 

The enum true is 0 in this case.

so:

0==(2==3)
0==(0)
1

1 is true. Thus this conditional is always true.

Kevin Montrose
thank u guysi owe you one
+5  A: 

It's because the default starting point for enums 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.

paxdiablo
This and Chris Arguin 's answer are the only ones that are both correct and complete.
Michiel Buddingh'
What do you mean, "guaranteed to work"? Comparing any non-zero value to 'true' using the == operator does not evaluate as true. E.g. 2==(1==1) evaluates as false. So in that sense, 'true' is 1 and only 1. Basically it's not valid to use == operator for boolean comparison.
Craig McQueen
No, I'm still dead set against comparing with true/false, you should use 'if(x)', not 'if(x==true)'. I mean (1==1) will give you the 'real' value of true (as the compiler sees it) rather than what you think it may be.
paxdiablo
It makes no difference if you understand the standard and how booleans work - this is just a trick for those yet to suffer the pain of 30 years of C coding :-)
paxdiablo
+6  A: 

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.

280Z28
A: 

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

Chris Arguin
+1  A: 

Because true is false and false is true.

Jack Leow
"this statement is false" :-)
beggs