'What is the most efficient way to test if a pointer is null?
What is most efficient between the two ways of testing pointer nullity : if(pointer==NULL) or if(!pointer).
MyObject* p;
[...]
// Solution 1
if ( p )
{ // Do something
}
// Solution 2
if ( p!=NULL )
{ // Do something
}
Solution 1:[1]
It makes no difference what so ever. It's purely a style issue what you prefer.
By the way, you should use nullptr rather than NULL if you use C++11 or later.
Solution 2:[2]
I prefer if (ptr) because:
- It is short and clear
- It doesn't depend on
NULLkeyword. Which have to benullptron C++11 or later as Jesper Juhl mentioned. - From SoapBox's comment on stackoverflow:
They are compatible with C++ classes such as auto_ptr that are objects that act as pointers and which provide a conversion to bool to enable exactly this idiom. For these objects, an explicit comparison to NULL would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the bool conversion implies.
Solution 3:[3]
Those are same. It makes no change in your program whatever you use.
Solution 4:[4]
I'd rather prefer the if (p!=NULL) as it prevents form accidental errors like casting the p in other thing, like an int for instance, between the declaration and the use of it.
Here the compiler should warn as int differ form NULL (initially NULL=(void*)0)
Furthermore i prefer to declare like this :
MyObject* p=NULL;
because you cannot assure that p wont have a value different of zéro. If you miss to instantiate it between declaration and use.
And it is less misleading than the
if (p==NULL){} else {} which may occur in an accidental assignment (only one =)
Off course in the C++11 or later this could involve some changes in your code even if the call of NULL is still working but deprecated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jesper Juhl |
| Solution 2 | Community |
| Solution 3 | Jisan Shaikh |
| Solution 4 | msc |
