gpt4 book ai didi

c++ - 编译器是否以类似方式对待 int 和 bool 类型?

转载 作者:太空狗 更新时间:2023-10-29 23:23:25 25 4
gpt4 key购买 nike

如果我有以下代码:

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转换为一。这导致上面的代码结束测试 if 2 != 1。

现在回答是否execute();的问题在问题的片段中被调用应该是显而易见的:值 a将转换为 boolif声明,并且由于它不是零,它将转换为 true并导致调用 execute() .

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com