保证返回的 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
)表达式保证被计算为 0
或 1
。
如果您从 bool
表达式中得到不同的值,则意味着您正在上游调用一些未定义的行为。
关于c - C99中bool类型可以返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384763/