对 C/C++ 中的布尔值求和

发布于 2024-12-08 13:26:10 字数 241 浏览 3 评论 0原文

考虑下面的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

清风不识月 2024-12-15 13:26:10

C++ 标准的第 4.7 节(整数版本)说:

如果源类型为bool,则值false将转换为
零,值 true 转换为一。

4.9 节对浮点转换做出了同样的保证。

Section 4.7 (integer versions) of the C++ standard says:

If the source type is bool, the value false is converted to
zero and the value true is converted to one.

Section 4.9 makes the same guarantee for floating point conversions.

只等公子 2024-12-15 13:26:10

对于编译器来说,规则通常是 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

摇划花蜜的午后 2024-12-15 13:26:10

根据标准:

  • true 转换为 1
  • false 转换为 0

并且不需要将其强制转换为 int,因为转换为 int 是隐式的。

According to the standard:

  • true converts to 1
  • false converts to 0

And he cast to int is not necessary as the conversion to int is implicit.

我家小可爱 2024-12-15 13:26:10

David Schwartz 已经回答了 C++。对于 C99 标准,我们有 6.3.1.4:

当任何标量值转换为 _Bool 时,如果满足以下条件,结果为 0:
值比较等于0;否则,结果为 1。

由于标准 6.3.1.1 还明确指出 _Bool 受到整数提升的影响,因此很明显 _Bool 将始终为 0 或 1。

David Schwartz already answered for C++. For the C99 standard we have 6.3.1.4:

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文