Style question !condition agains condition == NULL
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 b开发者_StackOverflowetter:
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.
I prefer the first one in this case, as you are explicitly comparing the value to see if it's null (which happens to be 0).
The second one reads as if fp
is a boolean, which it isn't.
It's like saying "Is this pointer invalid?" vs "Is this pointer false?"
Which one is more readable to you is, of course, a matter of opinion.
I prefer "=="; I think the reader has to think less. This is also why I detest typedefs.
Is it just a matter of style?
In the case of C, it is just a matter of style as both are correct, but in general, I believe more people (including me) prefer an explicit comparison (ptr == NULL
) as evidenced by the following:
- C++0x introduces a
nullptr
keyword to emphasize that it is more than just a mere number or boolean value. - Java forces explicit comparisons (
obj == null
) and does not allow!obj
.
Yes, this is matter of style. fp == NULL
(oops, I wrote fp = NULL
...) is very clear and explicit in that it express, and it is good for those not familiar with all C's twists and turns. Altough !fp
is very like an idiom and pun: "there's not(!)hing at fp". Ant it is short. For this i like !fp
. I think C designers also like this otherwise they should not define !
for pointers. :)
精彩评论