Pointer abort protection?

Hey folks,

I found following code snippet:
(that is all)

ptr != 0 && ptr->next();

I don't understand the idea. Can somebody
explain this to me?


cheers,
SC
It's a (bad) way of testing whether ptr is null before trying to use it. It relies on short circuit evaluation (if the left side of a && b is false, b doesn't have to be evaluated because we know the entire expression will return false).

That would be best expressed as:

if(ptr == 0) ptr->next();
Last edited on
hrm if(ptr != 0) ptr->next();
Thanks :)
Hey folks,

It relies on short circuit evaluation (if the left side of a && b is false, b doesn't have to be evaluated because we know the entire expression will return false).


I read the same. In every case the left side is zero/false. So we never touch ptr->next().
Where is my protection, if I'll never can start ptr->next();
You understand my problem?


Cheers,
SC :)
Firstly, you should bear in mind what filipe said - that this is not a great way of testing for a null pointer.

However, as for how it works: the thing you want to be protected from is trying to call a member function of the object pointed to by the pointer when that pointer is 0 (i.e. it doesn't point to anything). This would result in a runtime error.

But with that code, if ptr == 0 then ptr != 0 is false so the second statement, ptr->next() is not executed. Therefore if the pointer is null, its function is not called to prevent an exception.

In every case the left side is zero/false

If ptr != 0 is always false then ptr == 0 is always true. If your pointer is always null, then why are you trying to call a function through it?
Topic archived. No new replies allowed.