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
}
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
}
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.
I prefer if (ptr)
because:
NULL
keyword. Which have to be nullptr
on C++11 or later as Jesper Juhl mentioned.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.
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.