Reputation:
Is it recommended in c to write conditionals like this
if(foo != 0) {
// do stuff
}
Or like this
if(foo) {
// do stuff
}
I know they will always produce the same result, but which method is recommended for readability?
Upvotes: 2
Views: 12146
Reputation: 153517
Consider the various types that foo
may have. What is best is context sensitive.
I favor the first in each group.
void *fooptr = bar();
if (fooptr) ...
if (fooptr != NULL) ...
if (fooptr != 0) ...
int fooi = bar();
if (fooi != 0) ...
if (fooi) ...
double foofp = bar();
if (foofp != 0.0) ...
if (foofp) ...
bool foobool = bar();
if (foobool) ...
int (*foofun)() = bar();
if (foofun) ...
if (foofun != NULL) ...
if (foofun != 0) ...
But avoid foolish ones
if (foobool == 0.0) ...
if (fooi != NULL) ...
And I did not even touch the Yoda style (trying to avoid a holy war)
if (0 == foo) ...
In general, seeing code in the positive sense if(foo)
vs. if (foo != 0)
, is conceptually simpler. And I prefer if(foo == NULL)
to if(!foo)
You not think it isn't less understandable to avoid negating negatives, no?
Upvotes: 5
Reputation: 1
I believe that if(foo != 0)
is more clear. It some how also shows that foo is something that can be compared to 0
.
When I see if(foo)
is foo
a bool
or is it something else?
Upvotes: 0