The behavior depends on the language and on the type of the value being tested. The two forms are not equivalent in all cases.
In C, conditions are commonly represented using integers, with 0
being treated as false and any non-zero value being treated as true. Comparing such a value for equality to true
is invalid; for example, if the value happens to be 2 or -1, it's logically true but not equal to true
. As of C99, C does have a built-in boolean type called _Bool
, aliased as bool
if you have #include <stdbool.h>
. But it's still common to use other types, particularly int
to represent conditions, and even to redefine bool
, false
, and true
in various ways.
C++ has has a built-in bool
type, with false
and true
literals, since very early in its development, but it still retains much of its C ancestry. Other C-inspired languages are likely to have similar issues.
In languages that have a built-in boolean type and don't allow values of other types to be used directly as conditions, if (x)
and if (x == true)
are more likely to be equivalent. And if they're semantically equivalent, I would expect any decent optimizing compiler to generate the same code for either form, or very nearly so.
But I strongly disagree with the style advice. An explicit comparison to false
or true
, even in cases where it's equivalent to testing the value directly, do not IMHO aid readability.
If you have a variable whose value denotes a condition, it's more important to give it a name that indicates that. Programming language code shouldn't necessarily follow English grammar, but something like
if (file_is_open)
is not made more readable by changing it to
if (file_is_open == true)
As a C programmer, I like to write my conditions more explicitly than a lot of other programmers do; I'll write if (ptr != NULL)
rather than if (ptr)
, and if (c != '\0')
rather than if (c)
. But if a variable is already a condition, I see no point in adding a superfluous comparison.
And value == true
is itself a condition; if if (value == true)
is supposed to be more readable than if (value)
, why wouldn't if ((value == true) == true)
be even better?