In C++ bool
is a standalone type that has nothing to do with unsigned char
. And in C++ language the expression under if
is indeed implicitly cast to bool
type. Note: to bool
specifically, not to int
. For scalar types other than bool
, the implicit conversion to bool
is essentially defined through non-equality comparison to literal 0
. I.e. values that compare non-equal are converted to true
, while values that compare equal - to false
.
In other words, in C++ statement
if (a)
is interpreted as
bool tmp = (bool) a;
// `tmp` is either `true` or `false`
if (tmp)
which for scalar types is interpreted as
bool tmp = a != 0;
if (tmp)
Note that this works "as expected" for pointer types as well. But instead of converting the pointer to int
type, it actually works the other way around: it converts literal 0
to the proper pointer type.
For other types it could be something different, like a call to a user-defined conversion operator operator bool()
.
In C language the expression under if
has to have scalar type. And it is implicitly compared to constant 0
. Note that this does not involve converting the controlling expression it to int
. Comparison to constant 0
is defined separately for all scalar types. E.g. for int
it has its natural meaning, while for pointer types it is interpreted as comparison to null pointer. Now, the result of such comparison in C has type int
and evaluates to either 0
or 1
. That 0
or 1
is what controls what if
branch is taken.
In other words, in C statement
if (a)
is immediately interpreted as
int tmp = a != 0;
// `tmp` is either `0` or `1`
if (tmp)
Additionally, your assumption that null pointer produces a zero int
value when converted to int
type is incorrect. Neither language makes such guarantee. Null pointer is not guaranteed to be represented by zero address value and is not guaranteed to produce zero value when converted to int
.