difference between if(pointer) vs if(pointer != NULL) in c++, cpplint issue
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.
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++.
In C++, assuming ptr
is a pointer, the comparisons if (ptr)
and if (ptr != NULL)
are functionally equivalent.
In C++11 and later, it is often considered preferable to use the alternative if (ptr != nullptr)
.
For a simple check of a pointer, the differences in these options are really stylistic. The mechanisms might differ slightly, but the end result is the same.
cpplint, like most automated checkers, tends to - by default - complain more about breaches of some style guidelines more than others. Whether any particular set of guidelines is right or wrong depends on what is needed for your project.
For class types that can sensibly be compared with a pointer (e.g. smart pointer types) the preferred test depends on what set of operations (comparison operators, implicit conversions, etc) that type supports.