c - C99中bool类型可以返回什么?

标签 c standards arithmetic-expressions integer-arithmetic

保证返回的 bool 值是什么?我可以依赖 bool 类型始终被解释为 0 或 1 吗?如果 bool 的数值解释在 C99 中不可靠,是否有标准?当依赖 bool 进行算术运算时,在 LLVM、GCC 或 Visual C++ 中有什么我应该注意的吗?

举个例子,如果我这样做会怎样:

// An example of calculating a possible stride in bytes.
// hasData(), is8bit(), and is16bit() return as bool type

unsigned int stride = object->hasData() * object->size() * 
                      (object->is8bit()  * sizeof(uint8_t) + 
                       object->is16bit() * sizeof(uint16_t));

在这个例子中,我打赌 bool 类型只返回 0 或 1。

最佳答案

What is bool guaranteed to return as? Can I rely on a bool type to always be interpreted as 0 or 1?

在一个严格符合的程序中,_Bool(或 stdbool.h 中的 bool)表达式保证被计算为 01

如果您从 bool 表达式中得到不同的值,则意味着您正在上游调用一些未定义的行为。

关于c - C99中bool类型可以返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384763/

相关文章:

c++ - 在初始化列表中创建的 C++ 值是否进入堆栈?

c++ - 为什么 std::experimental::filesystem::path 不接受像 "*"这样的通配符?

c - C中的算术运算

c - 如何在 ruby​​ c 扩展中覆盖 rb_ 函数?

c - 无法使用 C 编译器打开包含文件 "Protocols.h"

c++ - 不稳定类型特征背后的原因是什么?

bash - 在 bash 中四舍五入到最接近的 2 的幂

c++ - 推导模板参数表达式的类型

c - 如何在c中给蒙版上色

c - 当用户输入正整数而不是字符时打破循环