When you use the if
statement in C/C++, or any other logical operator, is the operand you pass to the statement cast to an integer for evaluation?
My current understanding was that the operand passed to the statement is cast to an integer to test whether or not it is non-zero (true
), and that if you pass a pointer, this can be cast to an integer to evaluate with a 0/null
value being defined as false
.
I was under the impression that C++'s standard Bool
values were simply typedef
of an unsigned char
with a value of 0
and 1
.
Can anyone explain what's actually happening behind the scenes with this behavior?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With