Is this correct

R

Ravi Uday

Hi,

Can some-one comment on below snippet ?

static int xxx_list_compare (void *ptr1, void *ptr2) {
if (ptr1 && ptr2 && (ptr1 == ptr2)) {
return (0);
}
return (1);
}

Are bit operations and comparing operations allowed on void * ?
Any redundancy in the code.

thanks,
- ravi
 
N

Nelu

Ravi said:
Hi,

Can some-one comment on below snippet ?

static int xxx_list_compare (void *ptr1, void *ptr2) {
if (ptr1 && ptr2 && (ptr1 == ptr2)) {
return (0);
}
return (1);
}

Are bit operations and comparing operations allowed on void * ?

ptr1 and ptr2 are pointers and it's valid to use the operations you are
using.
It doesn't matter what the underlying type for the pointer is.
You do not have bit operations in your code. && is a logical operator
and ptr1 as a condition is true if ptr1 is not NULL. You can always
compare two pointers to see if they point to the same address.
Any redundancy in the code.
Yes. You are trying to do something if the pointers are not null and
they
point to the same address. You can rewrite the condition as:
if(ptr1&&(ptr1==ptr2)) because ptr2 is not going to be null if it
equals the non-null ptr1.
 
K

Keith Thompson

Ravi Uday said:
Can some-one comment on below snippet ?

static int xxx_list_compare (void *ptr1, void *ptr2) {
if (ptr1 && ptr2 && (ptr1 == ptr2)) {
return (0);
}
return (1);
}

Are bit operations and comparing operations allowed on void * ?
Any redundancy in the code.

No, bit operations on void* are not allowed. Fortunately, there are
no bit operations in the code you posted. Equality comparisons are
perfectly ok.

The function returns 0 if both arguments are non-null and are equal to
each other; otherwise it returns 1. If that's what you want, it
looks correct.

Personally, I'd prefer to make the comparisons explicit, and I never
use parentheses on a return statement (they make it look too much like
a function call):

if (ptr1 != NULL && ptr2 != NULL && ptr1 == ptr2) {
return 0;
}
else {
return 1;
}

or perhaps even this:

return ptr1 == NULL ||
ptr1 == NULL ||
ptr1 != ptr2;
 

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

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,490
Latest member
Finplus

Latest Threads

Top