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?
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?
if (foofp != 0.0) ... // is not the same as if (!(foofp == 0.0)) ... ?foofp is a number then? Are they not the same? Or are they ALWAYS the same? @chux-reinstate-monicafoofp is infinite or finite like 0 or 42.123. When a NaN is involved, a != b is commonly the same as !(a == b), yet C is squishy on that point (its an implementation detail). IEEE 754 specifies that are the same, but C does not specify IEEE 754 adherence.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?
_Bools, and with stdbool.h they are called bool like in C++. See en.cppreference.com/w/c/types/boolean
if ( 0 != foo ) {.foois an integer quantity that can have many values, and the second whenfoois a boolean (1/0, yes/no, true/false) quantity. Not to say thatfoohas to be declared as abool, but simply thatfoohas the semantics of a boolean.if (foo=0)which not only evaluates always asfalse, but it changes the value offoowhen it shouldn't. If you use to write comparisons placing the constant operand first, then the operator, then the other operand, an attempt to write:if (0=foo)will cause the compiler to trigger the obvious error