对 C/C++ 中的布尔值求和
考虑下面的 C++ 代码:
bool a = 5;
bool b = 6;
int c = (int)a + (int)b;
当我编译并运行此代码时,c 的值为 2。标准是否保证在任何编译器/平台中,用 false (0) 或 true(不一定是 1)初始化的 bool 值将为 1在运算中,上面的代码总是会导致 c 为 2?
在 C99 中,包括 stdbool.h,这仍然有效吗?
Consider the C++ code below:
bool a = 5;
bool b = 6;
int c = (int)a + (int)b;
When I compile&run this code, c has the value 2. Does the standard guarantee that, in any compiler/platform, bool values initialized with false (0) or true (not necessarily 1) will be 1 in operations and the code above will always result in c being 2?
And in C99, including stdbool.h, is that still valid?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C++ 标准的第 4.7 节(整数版本)说:
4.9 节对浮点转换做出了同样的保证。
Section 4.7 (integer versions) of the C++ standard says:
Section 4.9 makes the same guarantee for floating point conversions.
对于编译器来说,规则通常是 false 为 0,其他任何值都为 true。然而,将 bool 视为整数类型通常被认为是不好的形式。然而,标准包括转换为 int 的规则,只要编译器遵守标准,您的假设就是正确的 false = 0 和 true = 1!
无论如何,为什么要使用 bool 类型进行算术呢?
希望这有帮助
For compilers, the rule is often that false is 0 and anything else will be true. However, treating bool like it is an integer type is usually considered bad form. The standard however include a rule to convert to int and you assumption is correct false = 0 and true = 1 as long as the compiler adhere to the standard!
In any case, why arithmetic with bool types?
Hope this help
根据标准:
true
转换为 1false
转换为 0并且不需要将其强制转换为
int
,因为转换为int
是隐式的。According to the standard:
true
converts to 1false
converts to 0And he cast to
int
is not necessary as the conversion toint
is implicit.David Schwartz 已经回答了 C++。对于 C99 标准,我们有 6.3.1.4:
由于标准 6.3.1.1 还明确指出 _Bool 受到整数提升的影响,因此很明显 _Bool 将始终为 0 或 1。
David Schwartz already answered for C++. For the C99 standard we have 6.3.1.4:
Since 6.3.1.1 of the standard also makes it clear that _Bool is subject to integer promotions it's clear that a _Bool will always be either 0 or 1.