Emulating booleans in C can be done this way:
int success;
success = (errors == 0 && count > 0);
if(success)
...
With stdbool.h included following could be done:
bool success;
success = (errors == 0 && count > 0) ? true : false;
if(success)
...
From what I understand logical and comparison operators should return either 1 or 0.
Also, stdbool.h constants should be defined so that true == 1 and false == 0.
Thus following should work:
bool success;
success = (errors == 0 && count > 0);
if(success)
...
And it does work on compilers that I have tested it with. But is it safe to assume it is portable code? (Assume that stdbool.h exists)
Is the situation different on C++ compilers as bool is internal type?
It is safe to assume. In C99, upon conversion to the
_Booltype, all non-zero values are converted to 1. This is described in section 6.3.1.2 in the C99 standard. The equality and relational operators (e.g.==,>=, etc) are guaranteed to result in either 1 or 0 as well. This is described in section 6.5.8 and 6.5.9.For C++, the
booltype is a real Boolean type where values are converted totrueorfalserather than 1 or 0, but it is still safe to assign the result of an==operation etc. to abooland expect it to work, because the relational and comparison operators result in aboolanyway. Whentrueis converted to an integer type it is converted to 1.