I am working on a project to implement a Binary Search Tree, root is a pointer to a Node struct, and I ran into a piece of code online with the following line:
if ((root->left) && (root->right))
is the code above equivalent to:
if (root->left == root->right)
if not can someone please explain the difference to me? I thought you needed to have some sort of comparative operator (==, !=).
You did not post the code (and in C++ lot of things depend on context) but I believe that:
if ((root->left) && (root->right))
Is equivalent to:
if ((root->left != nullptr) && (root->right != nullptr))
The pointers in C++ can be implicitly converted to bool
that is true
when the pointer is a non-null pointer. The &&
operator means 'and'. So for the if
condition to be true
, both root->left
and root->right
are non-null pointers.
The relevant part from standard [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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.