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 is 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_ptrto1if eitherptr1is not NULL orptr2is not NULL, and0otherwise. You need to use the ternary operator: