【发布时间】:2017-11-26 18:54:53
【问题描述】:
给定以下 C11 代码:
int a = 1234;
bool b = (bool)a; // equivalent to (a != 0) or (a != false) which evaluates to 1 or true
if (a) // equivalent to if(a != 0) or if (a != false) which evaluates to 1 or true
printf("a\n");
if (a == (bool)true) // should be equivalent to if(!(a == false)) or if (a != false)
printf("a == (bool)true\n");
我知道 true 是 #define true 1,但 bool 显然不是普通的整数类型,因为像 (bool)0.1 这样的东西的计算结果为 1,而转换为 int 会导致 0。
1) 为什么true 没有定义为(bool)1?这将允许编译器至少输出一个警告。
2) 为什么我的示例中的整数没有转换为 bool 以使 a == (bool)true 的计算结果为 (bool)a == (bool)true 这实际上是正确的?
【问题讨论】:
-
即使它被定义为
(bool)1积分提升仍然会将a == true变成a == 1这是错误的。积分提升将始终“提升” bool 和 int,因为那是更广泛的类型。这就是进行促销的意义所在。 -
“为什么我的例子中的整数没有转换成
bool”——因为这不是整数提升在 C 中的工作方式。 -
_Bool是整数类型,但“编译器使用以下 hack”是不正确的。 This behavior is specified by the Standard -
bool是一个真正的布尔类型;布尔变量只能有 rwo 值。但是a不是布尔变量,它的值也不是布尔的可能性。我看不出有任何理由认为 C 应该选择将a转换为bool而不是在整数和布尔值之间的比较中将布尔值转换为int,但无论您是否可以证明这一点选择,这不是 C 的工作方式。同样,在char a = 'A';之后,a == 321的值为false,即使a == (char)321为真。 -
@xnor -- 我不知道您为什么坚持称其为“hack”,而且它肯定不是编译器 hack。
_Bool的转换在标准 just like all other conversions 中明确描述。0.123被转换为非_Bool的整数类型时会被截断,并带有下划线here in the Standard。