Search code examples
c++pointerssyntaxreferenceboolean-expression

C++ - Difference between "!pointer" and "pointer == nullptr"?


So I came across this little snippet of code from a function

void remove(Node * & p, const int & key){
  if(!p){
    throw out_of_range("The key you're looking for can't be found\n");
  }
  if(p == nullptr){
    return;
  }

and I don't quite understand the difference between !p and p == nullptr. From what I have read about C++ it always seemed to be like these two statements are equivalent. Are they not? Am I wrong?

Need some clarifictation.

Thanks!


Solution

  • Actually both are same. You can check whether the pointer is null or not using both.

    nullptr was introduced in C++11 which can be used like if(p == nullptr) which is preferred over if(!p)

    Hope this helps :)