Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between if( pointer == NULL) and if(!pointer)?

Tags:

c++

pointers

What is the difference in between using:

if( pointer == NULL) 

And

if(!pointer)

I am concerned with the differences between the two in respect to the following points:
1. Are they different for the compiler? If yes, then how?
2. Which of the two is the recommended coding style for general use and why?
3. Can you please explain how NULL is "seen" by the compiler.

Edit: For the sake of simplicity let pointer be of type int *.

like image 895
gargakshat98 Avatar asked Aug 04 '26 09:08

gargakshat98


1 Answers

Assuming pointer is a pointer type, if (pointer == NULL) is anachronistic and poor C++ since the the null pointer value in C++ is nullptr in C++ with type nullptr_t.

if (!pointer) is the much preferred idiom.

like image 153
Bathsheba Avatar answered Aug 06 '26 01:08

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!