gpt4 book ai didi

c++ - if (intVar) 和 if (intVar != 0) 之间有区别吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:09:16 24 4
gpt4 key购买 nike

我很想知道这两个 if block 在 C++ 中是否有区别。如果您可以在答案中引用一些引用,那将非常有用。

if ( intVar!= 0 )
{
//Do something
}

if (intVar)
{
//Do samething
}

其中intVar,可以是任何类型的具有任何值的整型变量。

[编辑] 关于“重复问题”的主题。我没有发现任何涉及if语句的问题。

最佳答案

if 条件中要求的表达式类型为 bool 值。表达式 intVar!=0 已经是 bool 值,表达式 intVar 的类型为 int 并且需要隐式转换为 bool 值。 intbool 的转换规则正好是任何非零映射到 true 和零映射到 false,所以得到的表达式求值是完全一样的。

有时写完整的 intVar!=0 可以增加清晰度(例如,要明确表示您不是在评估 nullptr 的指针类型,而是在计算一个整数键入零),而其他时候则不会 - 这实际上取决于上下文。

关于请求的引用,我将使用 standard .与转换相关的部分 [conv.bool]:

4.14 Boolean conversions

A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to aprvalue of type bool. A zero value, null pointer value, or null memberpointer value is converted to false; any other value is converted totrue

关于c++ - if (intVar) 和 if (intVar != 0) 之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40978251/

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