Search code examples
c++pointerscoding-stylecpplint

difference between if(pointer) vs if(pointer != NULL) in c++, cpplint issue


I already checked this post Can I use if (pointer) instead of if (pointer != NULL)? and some other posts on net.

But it is not stating any difference between two statements.

Problem: As I run cpplint.py on my cpp code, I found issues where I check pointers for NULL. I preferred to check using simple

if(pointer)         //statement1

but cpplint says you should check like

if(pointer != NULL)        //statement2

So I just want to know , Are there any benefits of statement2 over statement1 ? Are there some scenarios in which statement1 may create problem ?

Working: As per my knowledge there is no difference in working of both statements. Its just a change of coding style.

I prefer to use like statement1, because

  • Its Simple, Readable
  • No Tension of missing (=) by mistake over equality(==) in a comparison

But cpplint is raising this as issue, then there might be some benefit that I missed.

Note: Java also doesn't support statement1.


Solution

  • No, if pointer is really a pointer type there is no difference, so everything here is a question of coding style. Coding style in turn depends on habits in different communities so there can't be a general recommendation.

    I personally prefer the first because it is shorter and more to the point and avoids the use of the bogus macro NULL.

    In C NULL can be very different things (integer or pointer) and in C++ its use is even deprecated nowadays. You should at least use nullptr, there.