Search code examples
cbooleancomparison-operatorsc-standard-library

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

  • How can this happen? Are the variables a and b being filled with the value 0x1 in the assignment regardless of what I assign to them? Or maybe is it the == that has been hacked to handle bools?
  • Is this behaviour portable accross C Standard Library implementations and compilers?
  • What was the correct way of logically comparing two bool/int before the introduction of stdbool.h ?

Solution

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