If you call some function, and that functions returns NULL in case of an error (think of malloc()
or fopen()
for example), which of the two is better:
FILE *fp = fopen(argv[0], "r");
if (fp == NULL) {
// handle error
}
or
if (!fp) {
// handle error
}
Is it just a matter of style? I think the first one is clearer being more explicit but then I rarely code in C :-).
I prefer comparing with NULL, because it makes it clear that both operands of the comparison are supposed to be pointers. This
(!p)
or this
(p == 0)
require that you know what p's type is (an integer? a boolean?) at a glance. I am of the opinion that all coding should be done with the assumption that you are going to have to debug the thing at 4am (that's 4 in the morning, for the sleepless out there) 9 months later. In that case every little bit helps.
Oh, and it's good practice to place constants as the first operand when testing for equality, so that the compiler will abort with an error if you accidentally turn it into an assignment.
I believe this is a matter of style. Personally, I like the second option better. Others like the first one because it is clearer and more "proper". Some people even write if (NULL == fp)
so they can never accidentally forget one =
and turn it into an assignment. All in all though, I think it's a matter of taste, and it's probably more important to be somewhat consistent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With