What does "!" mean in syntax like this?

I'm normally used to seeing things like x != y, but we started using trees in my class recently, and I'm not sure what it means in syntax like this.



 
  if (!node)  return;
It means "not", just as it does in x != y. It's shorthand for:

if (node == false)

which in turn is equivalent to:

if (node == 0)

or:

if (node == nullptr)



Last edited on
See logical operators in http://www.cplusplus.com/doc/tutorial/operators/

Classes can define their own operator!. For example: http://www.cplusplus.com/reference/ios/ios/operator_not/
Actually it means to invert the current value.

If node == false, putting ! in front will evaluate to true.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main() {
	
	bool node = false;
	cout << node << " " << !node;

	cin.ignore();
	cin.get();
	return 0;
}
It means to invert the truthiness of the value, not he value itself.
I have seen code like this, to toggle a bool value...

1
2
3
4
5
6
7
8
9
bool b = false;

if(b== false) {
b = true;
}

else {
b = false;
}


This can be written as b = !b;
> if (!node) return;

There are certain contexts in C++ where an expression of type bool is expected; for example, when an expression is used as an argument to a built-in logical operator (!, && or ||). In such cases, a non-bool expression is
contextually converted to bool and the operator is applied to the (bool) result of the conversion.

To evaluate: !node
Convert node to bool (covert pointer to bool, the result is false if the pointer is null, true otherwise).
Apply the logical operator ! to the result of the conversion.

if (!node) return; is conceptually equivalent to:
1
2
3
4
const bool not_null = node ; // not_null is true if node != nullptr is true
const bool is_null = !not_null ; // negation of not_null; is_null is true if not_null is false;
                                 // ie. is_null is true if node == nullptr
if( is_null ) return ;



Topic archived. No new replies allowed.