C pointers and || operators
I'm just wondering whether this is "good" code for a C89 program.
obj_ptr = (obj*) (ptr1 || ptr2);
Essentially what it does (atleast in GCC on my computer) is set obj_ptr as ptr1 if ptr1 != NULL and ptr2 otherwise.
I've looked around and I can't see whether this i开发者_JAVA技巧s proper, but judging by the fact that the || operator has to convert the pointers to integers and then I have to cast them back is a hint of bad style.
If this is bad style or unportable, and is there a better and (hopefully) equally as terse solution?
EDIT: My primary concern whether the code I have written is portable and doesn't rely on undefined behavior.
I may have found a better way which is portable and which I think is "good style" (unless you don't like assignment in if statements).
if(!(obj_ptr = ptr1))
obj_ptr = ptr2;
No, what it does is set obj_ptr
to 1
if either ptr1
is not NULL or ptr2
is not NULL, and 0
otherwise. You need to use the ternary operator:
obj_ptr = ptr1 ? ptr1 : ptr2;
Well, it would definitely be invalid in C++ (where both operands are promoted to bool
). I admit I am not sure about C.
[Update] OK, found it, C99 spec section 6.5.14:
Semantics
The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
So ||
always evaluates either to 0 or to 1.
The usual way to formulate that expression is:
obj_ptr = (ptr1 ? ptr1 : ptr2);
If you actually need the (obj *) cast, there is a good chance you are doing something wrong.
if you don't like writing ptr1 twice, you can use a macro:
#define or(a, b) (a ? a : b)
obj_ptr = or(ptr1, prt2);
精彩评论