Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 517
ashish Avatar asked Jul 31 '16 10:07

ashish


2 Answers

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.

like image 106
Jens Gustedt Avatar answered Nov 02 '22 06:11

Jens Gustedt


You are using Hungarian notation, where it's possible to tell if a variable is a pointer. As long as it is - either native or smart - there's no difference. However, when someone changes it to another indirect type (e.g., std::optional<>), then the second will fail. So my suggestion is to keep on using the first: it's not Java, it's C++.

like image 39
lorro Avatar answered Nov 02 '22 08:11

lorro