Hobber
Hobber

Reputation: 192

Compare two bools with different int value

#include <stdbool.h>                                                            
#include <stdio.h>                                                                 
int main ()                                                                        
{                                                                                  
    bool a, b;                                                                     
    a = 1;                                                                         
    b = 4;                                                                         
                                                                                   
    if (a == b)                                                                    
        printf ("They are equal\n");                                               
    else                                                                           
        printf ("They are different\n");                                           
}

This code prints They are equal

Upvotes: 0

Views: 278

Answers (2)

P.P
P.P

Reputation: 121427

C11, 6.3.1.2 says:

When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

When you assign 4 to b, it's simply assigned to 1. So yes, this behaviour is guaranteed by the C standard.

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 142080

How can this happen?

Both variables are 1, so they are equal.

Are the variables a and b being filled with the value 0x1 in the assignment regardless of what I assign to them?

Well, not regardless. Any non-zero value is converted to 1 and assigned to bool. A zero value will fill them with... 0.

Or maybe is it the == that has been hacked to handle bools?

No.

It's that bool is a macro that expands to _Bool and that _Bool variables have special semantics when assigning a value to it.

Is this behaviour portable accross C Standard Library implementations and compilers?

Yes.

What was the correct way of logically comparing two bools before the introduction of stdbool.h ?

When bool is not an _Bool, but like an int, you can convert the values on assignment or comparison to 0 or 1 with double logical NOT:

if (!!a == !!b)      

Upvotes: 1

Related Questions