Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style question !condition agains condition == NULL

Tags:

c

coding-style

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 :-).

like image 556
helpermethod Avatar asked Nov 28 '10 20:11

helpermethod


2 Answers

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.

like image 189
thkala Avatar answered Sep 28 '22 02:09

thkala


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.

like image 42
EboMike Avatar answered Sep 28 '22 04:09

EboMike