C/C++ `!a` vs `a==0`

c, c++

Solution

It's unlikely there will be a difference in performance, because compilers know about the logical equivalence and so there's no reason they can't emit identical code for both.

The equivalence is elementary, not some clever theorem: the meaning of `!a` for integer types defined in the standards is "value of `a` equal to 0" (or strictly speaking as James points out, "not (value of `a` not 0)"), and the meaning of `!a` for pointer types is "`a` is a null pointer" (or strictly speaking "not (value of `a` is a non-null pointer)".

However, there's no requirement that a compiler must emit identical code for both, so it's not guaranteed by the C or C++ standard that performance is identical.

Problem

When I have an integer or a pointer `a`, it turns out that both ``` !a ``` and ``` a==0 ``` have the same behavior. At a very low level, is there some difference in terms of speed of computation?

Original source

Related problems