9
I'm working on a C program. There is a function which takes two pointer arguments, call it cmp(). I present here a simplified stand-in for cmp() for illustrative reasons:
int cmp(struct foo *a, struct foo *b)
{
return a->bar == b->bar;
}
I'd like to make a NULL-check macro, like this:
#define SAFE_CMP(a,b) (((a) != NULL && (b) != NULL) ? cmp((a),(b)) : 0)
I think this is perfectly fine. However, in when compiling with both -Wall and a compliation switch that regards a warning as an error, the following code is troublesome:
int baz(struct foo *a)
{
struct foo b;
/* ... */
return SAFE_CMP(a, &b);
}
since gcc warns that "the address of b will never be NULL".
Is there any way to workaround this situation?
Having various helper macro like SAFE_CMP_1(safe_arg,unsafe_arg) and SAFE_CMP_2(unsafe_arg,safe_arg) etc. is the last thing I want. I'd like to have one helper macro applicable to all situations.