Anonymous
Anonymous

Reputation: 4197

Testing for a non-null pointer, and returning null otherwise

I'm wondering whether it's considered okay to do something like this.

if ( p_Pointer != NULL ) {
  return p_Pointer;
} else {
  return NULL;
}

Without the else, whatever. The point is that if the pointer is null, NULL is going to be returned, so it would seem pointless wasting a step on this. However, it seems useful for debugging purposes, because if I was stepping through with a debugger I would be able to check with this test if the pointer is NULL or not.

Any comments or suggestions regarding this practice?

Upvotes: 3

Views: 899

Answers (4)

Roboprog
Roboprog

Reputation: 3144

Use a conditional breakpoint (on the would-be single "return" line) instead?

Upvotes: 1

justin
justin

Reputation: 104698

As it is, it looks really weird. If you actually do more, or it the expression is used regularly, then that would dispel suspicions.

With a little more, it is not so unusual:

    if ( p_Pointer != NULL ) {
      return p_Pointer;
    } else {
      assert(p_Pointer);
      return NULL;
    }

or

    assert(p_Pointer);
    return p_Pointer;

oder vielleicht:

    return require_valid_pointer(p_Pointer);

Upvotes: 1

Graeme Perrow
Graeme Perrow

Reputation: 57248

It's "okay" to do this, i.e. there's nothing wrong with it, although it's not very useful. If you're stepping through in a debugger, you should be able to display the value of p_Pointer anyway.

It's similar to

if( flag == TRUE ) {
    return TRUE;
} else {
    return FALSE;
}

rather than just return flag;

Upvotes: 8

Khaled Alshaya
Khaled Alshaya

Reputation: 96879

You could just say:

return p_Pointer;

Because the if statement is superfluous in that case.

Upvotes: 6

Related Questions