是C / C ++布尔类型始终保证typecast'ed为int时为0或1?

编程入门 行业动态 更新时间:2024-10-09 07:26:23
本文介绍了是C / C ++布尔类型始终保证typecast'ed为int时为0或1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

许多编译器似乎只保留0或1的布尔值,但我不知道这将始终工作:

int类型的= 2;布尔B = A;INT C = 3 + B; // 4或5?

解决方案

是:

在C ++(§4.5/ 4):

  

bool类型的右值可  转换成int类型的右值,  以虚假成为零和真  成为一体。

在C,当值转换为 _Bool ,就变成0或1(§6.3.1.2/ 1):

  

当任何标值被转换为  _Bool,结果是0,如果值进行比较等于0;否则,  结果是1。

当转换为 INT ,这是pretty直线前进。 INT 可容纳0和1,所以有一个在价值没有改变(§6.3.1.3)。

Many compilers seem to be keeping only 0 or 1 in bool values, but I'm not sure this will always work:

int a = 2; bool b = a; int c = 3 + b; // 4 or 5?

解决方案

Yes:

In C++ (§4.5/4):

An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.

In C, when a value is converted to _Bool, it becomes 0 or 1 (§6.3.1.2/1):

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

When converting to int, it's pretty straight-forward. int can hold 0 and 1, so there's no change in value (§6.3.1.3).

更多推荐

是C / C ++布尔类型始终保证typecast'ed为int时为0或1?

本文发布于:2023-11-16 03:53:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1600752.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:布尔   类型   typecast   int   ed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!