State of style! Condition again condition == NULL

If you call some function and that function returns NULL in case of an error (for example, malloc() or fopen() ), which of the two is better:

 FILE *fp = fopen(argv[0], "r"); if (fp == NULL) { // handle error } 

or

 if (!fp) { // handle error } 

Is this just a matter of style? I think the first one is clearer, more explicit, but then I rarely code in C :-).

+6
c coding-style
source share
6 answers

I prefer to compare with NULL because it makes it clear that both comparison operands must be pointers. it

(! R)

or

(p == 0)

require you to know what a p-type (integer? boolean?) is at a glance. I am of the opinion that all coding should be done with the assumption that you have to debug this thing at 4 a.m. (it's 4 a.m., for insomnia there) 9 months later. In this case, every bit helps.

Oh, and it's good practice to put constants as the first operand when testing for equality, so that the compiler aborts the error with the error if you accidentally turned it into a task.

+7
source share

I think this is a matter of style. Personally, I like the second option better. Others, like the first, because it is clearer and more "correct." Some people even write if (NULL == fp) so they can never accidentally forget one = and turn it into a task. In general, although I think it is a matter of taste, and it is probably more important to be somewhat consistent.

+7
source share

I prefer the former in this case, since you are explicitly comparing the value to see if it is null (which happens to be 0).

The second reads as if fp is Boolean, but it is not.

I like to say, "Is this pointer invalid?" vs "Is this pointer false?"

Which one is more readable for you is, of course, a matter of opinion.

+3
source share

I prefer "=="; I think the reader needs to think less. This is why I hate typedefs.

+2
source share

Is this just a matter of style?

In case of C, this is just a matter of style, since both are correct, but in general I believe that more people (including me) prefer explicit comparisons ( ptr == NULL ), as evidenced by the following:

  • C ++ 0x introduces the nullptr keyword to emphasize that it is more than just a number or a boolean.
  • Java forces explicit comparisons ( obj == null ) and does not allow !obj .
+1
source share

Yes, it is a matter of style. fp == NULL (oops, I wrote fp = NULL ...) is very clear and clear in what it expresses, and this is good for those who are not familiar with all the turns C. Altough !fp very similar to an idiom and a pun : "There is no (!) Hing with fp." Ant he's short. For this I like !fp . I think C designers also like this, otherwise they should not define ! for pointers. :)

0
source share

All Articles