Is C/C++ bool type always guaranteed to be 0 or 1 when typecast#39;ed to int?(当类型转换为 int 时,C/C++ bool 类型是否总是保证为 0 或 1?)
问题描述
许多编译器似乎只在 bool 值中保留 0 或 1,但我不确定这是否总是有效:
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?
推荐答案
是的:
在 C++ 中(第 4.5/4 节):
In C++ (§4.5/4):
bool 类型的右值可以是转换为 int 类型的右值,假变成零和真合而为一.
An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.
在 C 中,当一个值转换为 _Bool 时,它变为 0 或 1(第 6.3.1.2/1 节):
In C, when a value is converted to _Bool, it becomes 0 or 1 (§6.3.1.2/1):
当任何标量值转换为_Bool,如果值比较等于0,则结果为0;否则,结果是 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.
当转换为 int 时,它非常简单.int 可以容纳 0 和 1,因此值没有变化(第 6.3.1.3 节).
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).
这篇关于当类型转换为 int 时,C/C++ bool 类型是否总是保证为 0 或 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当类型转换为 int 时,C/C++ bool 类型是否总是保证为 0 或 1?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
