CodeTrek
CodeTrek

Reputation: 475

Avoiding stray pointers in if conditions involving AND

How does these two if condition evaluate in the case of avoiding stray pointers?

if (vShop[0].vItem[vShop[0].itsActiveItem]!=NULL && vShop[0].vItem[vShop[0].itsActiveItem]->itsQuantity>0) DoPurchase();

where vShop[0] is a vector of objects and vItem is a vector of pointers to objects.

I want to make sure that the pointer does not evaluate NULL before it further checks vShop[0].vItem[vShop[0].itsActiveItem]->itsQuantity>0.

Or should I have to do it separately, that is:

if (vShop[0].vItem[vShop[0].itsActiveItem]!=NULL) if (vShop[0].vItem[vShop[0].itsActiveItem]->itsQuantity>0) DoPurchase();

In other words does the first case is a sequential check and if the first condition evaluates, the second condition is automatically dropped? Many thanks.

Upvotes: 0

Views: 261

Answers (1)

Daniel Frey
Daniel Frey

Reputation: 56863

You can use the former, since && only evaluates the second condition if the first one was true. Hence code like

if ( p != NULL && p->age == 42 )

is perfectly valid.

Beward that this is only true if you are dealing with built-in types, the same assumption is no longer true when && is overloaded for UDTs, but for plain pointers, the above is fine and it is exactly what you need.

Upvotes: 3

Related Questions