比较两个具有不同 int 值的 bool

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");                                           
}

此代码打印 They are equal

How can this happen?

两个变量都是1,所以它们相等。

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

好吧,不管怎样。任何 非零 值都转换 为 1 并分配给 bool。零值将填充它们... 0.

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

没有

就是bool是一个扩展为_Bool的宏,_Bool变量在给它赋值时有特殊的语义

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

是的。

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

bool 不是 _Bool,而是像 int 时,您可以使用双重逻辑 NOT:[=23] 将赋值或比较中的值转换为 0 或 1 =]

if (!!a == !!b)      

C11, 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.

当您将 4 分配给 b 时,它只是分配给 1。所以是的,这种行为由 C 标准保证。