Express the intent
The driving principe should be to express intentions, i.e. what you really mean to achieve. This makes the code self-explanatory.
Applying this principe to integer comparisons with zero leads without a doubt to x==0
or x!=0
. This is simpler to understand than converting mentally into a boolean.
Is there a guidance in some coding style?
In very strongly typed languages, integers are not implicitly convertible to bool. No need for a coding style, the compiler will convince you, as this Swift example will show:
let x : Int = 12
if !x { // Error: Type Int cannot be used as a boolean. test for ==0 instead.
print ("x is false")
}
For more flexible typed languages such as C and C++, there is as far as I know no popular guidance for -- or against -- this style in C and C++. Not even in security standards such as MISRA.
The reason is backward compatibility with millions of lines of code that used this shortcut. Many of these lines were written before booleans made it to a real built-in types. And when integer variables represent booleans it makes sense, but in other cases there is no advantage for using the more compact version. Writing ==0
will produce the same code, and will be more readable if it's about integers values.
(Important remark: Nowadays, this idiom continues to be popular also for non numeric types. while(cin)
or if (!cin)
areused as popular idom for checking that a stream is in a valid or a faulty status. Abandoning this idiom might create more confusion than it resolves. It might even lead to faulty code if you want to replace while(cin)
with while(!cin.eof())
due to the stream semantics.)
!x
is invalid ifx
is an integer.