在 C++ 中使用“&&”运算符意味着什么?
What does this use of the '&&' operator mean in C++?
我正在做一个实现二叉搜索树的项目,root 是一个指向 Node 结构的指针,我 运行 使用以下行在线编写一段代码:
if ((root->left) && (root->right))
上面的代码是否等同于:
if (root->left == root->right)
如果不是,有人可以向我解释一下区别吗?我认为您需要某种比较运算符(==、!=)。
您没有 post 代码(在 C++ 中很多事情取决于上下文)但我相信:
if ((root->left) && (root->right))
相当于:
if ((root->left != nullptr) && (root->right != nullptr))
C++中的指针可以隐式转换为bool
,即指针为非空指针时true
。 &&
运算符表示 'and'。所以对于if
条件为true
,root->left
和root->right
都是非空指针
标准中的相关部分[conv.bool]
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to
member type can be converted to a prvalue of type bool. A zero value,
null pointer value, or null member pointer value is converted to
false; any other value is converted to true. For direct-initialization
, a prvalue of type std::nullptr_t can be converted to a prvalue
of type bool; the resulting value is false.
我正在做一个实现二叉搜索树的项目,root 是一个指向 Node 结构的指针,我 运行 使用以下行在线编写一段代码:
if ((root->left) && (root->right))
上面的代码是否等同于:
if (root->left == root->right)
如果不是,有人可以向我解释一下区别吗?我认为您需要某种比较运算符(==、!=)。
您没有 post 代码(在 C++ 中很多事情取决于上下文)但我相信:
if ((root->left) && (root->right))
相当于:
if ((root->left != nullptr) && (root->right != nullptr))
C++中的指针可以隐式转换为bool
,即指针为非空指针时true
。 &&
运算符表示 'and'。所以对于if
条件为true
,root->left
和root->right
都是非空指针
标准中的相关部分[conv.bool]
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization , a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.