如果我有以下代码:

int a = 1;
bool b = 1;

a 等于 b 吗?甚至程序可能会返回它们是相同的,它们实际上在低级别的各个方面都相同吗?

另外,如果我使用代码(伪),例如:
if (a)
then execute();
execute() 会运行吗?我在寻求理论答案,我无法通过实验说服自己,因为这不是自然科学。谢谢你们。

最佳答案

我认为你可以用 the right experiments 说服自己:

#include <type_traits>

int main() {
    int a = 1;
    bool b = 1;
    static_assert(! std::is_same<decltype(a), decltype(b)>::value,
                  "No, they are not the same on all aspects");
}

也许两者之间最重要的区别是 bool 只能有两个值: truefalse ,而 int 可以有更多。这是 another experiment 显示的结果:
#include <cassert>

int main() {
    int a = 2;
    bool b = 2;
    assert(a != b);
}

这两种类型可能看起来很相似,因为两者之间存在隐式转换。任何为零的整数表达式都可以隐式转换为 false ,任何不为零的整数表达式都可以隐式转换为 true 。在相反的方向,false 可以隐式转换为零,true 转换为 1。这导致上面的代码最终测试是否 2 != 1。

现在问题的片段中是否调用 execute(); 的问题的答案应该是显而易见的:值 a 将在 bool 语句中转换为 if,并且由于它不为零,它将转换为 true 并导致调用 execute()

关于c++ - 编译器是否类似地对待 int 和 bool 类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11354602/

10-11 23:19
查看更多