query pointer && *pointer: safe?

F

Felix Kater

Hi,

if I want to make sure that neither the pointer arg nor the value to
which it points to is NULL: Is solution (a) safe -- or does it have to
be like (b) ?
Felix

void f(int* p){

/* (a) */
if(p==NULL || *p==NULL) return;

/* (b) */
if(p==NULL) return;
if(*p==NULL) return;

}
 
G

Guest

Felix said:
Hi,

if I want to make sure that neither the pointer arg nor the value to
which it points to is NULL: Is solution (a) safe -- or does it have to
be like (b) ?

NULL is a null pointer constant. It might be a literal 0 on your
implementation, but this is not true on several others. If you're
comparing *p to NULL because p is a pointer to a pointer to something,
you should declare p as such. If you're comparing *p to NULL because
you want to know if it is zero, just check for 0. That said, the && and
|| operators don't evaluate their right operands if the result is known
from the left, so both ways are just as safe.
 
E

Eric Sosman

Felix said:
Hi,

if I want to make sure that neither the pointer arg nor the value to
which it points to is NULL: Is solution (a) safe -- or does it have to
be like (b) ?
Felix

void f(int* p){

/* (a) */
if(p==NULL || *p==NULL) return;

/* (b) */
if(p==NULL) return;
if(*p==NULL) return;

}

Both are wrong. Testing `p == NULL' is fine, but `*p' is
an int, not a pointer. On some systems, `*p == NULL' will get
an error message from the compiler.
 
F

Felix Kater

Eric Sosman said:
Both are wrong.

Please forgive. I meant an int** arg (not int*), while it is
additionally granted that the address of an int* is passed by
the client programmer. Is it safe in *this* case to evaluate both
like in (a)?
Felix

void f(int** pp){

/* (a) */
if(pp==NULL || *pp==NULL) return;

/* (b) */
if(pp==NULL) return;
if(*pp==NULL) return;

}
 
R

Richard Heathfield

Felix Kater said:

Please forgive. I meant an int** arg (not int*), while it is
additionally granted that the address of an int* is passed by
the client programmer. Is it safe in *this* case to evaluate both
like in (a)?
Felix

void f(int** pp){

/* (a) */
if(pp==NULL || *pp==NULL) return;

Yes, that's fine. If pp is NULL, the "or-expression" is true, and shortcut
evaluation means there is no need to evaluate the second part, and it WILL
NOT be done (this is guaranteed).
 
P

pete

Felix Kater wrote:
Please forgive. I meant an int** arg (not int*), while it is
additionally granted that the address of an int* is passed by
the client programmer. Is it safe in *this* case to evaluate both
like in (a)?

Yes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top