Is C/C++ bool type always guaranteed to be 0 or 1 when typecast’ed to int?

Yes:

In C++ (§4.5/4):

An rvalue of type bool can be
converted to an rvalue of type int,
with false becoming zero and true
becoming one.

In C, when a value is converted to _Bool, it becomes 0 or 1 (§6.3.1.2/1):

When any scalar value is converted to
_Bool, the result is 0 if the value compares equal to 0; otherwise, the
result is 1.

When converting to int, it’s pretty straight-forward. int can hold 0 and 1, so there’s no change in value (§6.3.1.3).

Leave a Comment