2

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
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Flows
  • 3,675
  • 3
  • 28
  • 52
  • 11
    I **highly** doubt they compile to different assembly. – BoBTFish Dec 16 '16 at 08:26
  • 4
    @BoBTFish I have no doubt. I can just try. https://godbolt.org/g/cCrgUb –  Dec 16 '16 at 08:37
  • According to me, what i have used in our project both works same.It depends on your code requirement which if condition you want to be satisfied according to what you want to be executed if, if satisfies to true.And most importantly make sure your pointer initialise to NULL before you use it further in If. – Sucheta AB Dec 16 '16 at 08:44
  • 1
    @NickyC They didn't mention a compiler, cpu architecture, OS, optimisation options... – BoBTFish Dec 16 '16 at 11:43

4 Answers4

12

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.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
6

I prefer if (ptr) because:

  1. It is short and clear
  2. It doesn't depend on NULL keyword. Which have to be nullptr on C++11 or later as Jesper Juhl mentioned.
  3. 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.

Community
  • 1
  • 1
Dulguun
  • 554
  • 5
  • 11
1

Those are same. It makes no change in your program whatever you use.

0

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.

msc
  • 33,420
  • 29
  • 119
  • 214
Patrice F
  • 31
  • 7