Assigning conditions to logical

Emulation of Boolean elements in C can be done as follows:

int success; success = (errors == 0 && count > 0); if(success) ... 

With stdbool.h enabled, the following can be:

 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. In addition, stdbool.h constants must be defined so that true == 1 and false == 0 .

So the following should work:

 bool success; success = (errors == 0 && count > 0); if(success) ... 

And it works on compilers with which I tested it. But can this be considered portable code? (Assume stdbool.h exists)

Is the situation different for C ++ compilers since bool is an internal type?

+6
source share
3 answers

It is safe to assume. In C99, when converting to the _Bool type _Bool all nonzero values ​​are converted to 1. This is described in section 6.3.1.2 of the C99 standard. Equality and relational operators (e.g. == , >= , etc.) ensure that there will be either 1 or 0. This is described in sections 6.5.8 and 6.5.9.

For C ++, the bool type is a real boolean type, where the values ​​are converted to true or false instead of 1 or 0, but it is still safe to assign the result of the operation == , etc. a bool and expect it to work, because that relational and mapping operators in any case lead to bool . When true converted to an integer type, it is converted to 1.

+15
source

The expression (errors == 0 && count > 0) is of type bool and can be used wherever bool is required, including assignment to a variable of type bool or its use in state. (When converting to another integral type, false converted to 0, and true to 1, but there are no questions in your code.)

Note that in C, with <stdbool.h> , bool should behave exactly the same as in C ++ (although for various historical reasons, the actual specification is different). This means something like:

 bool success = (errors == 0 && count > 0) ? true : false; 

- This is not what you would like to write. expression errors == 0 && count > 0 has a type that is equally compatible with bool and can be used as an expression of type bool . (In C ++, of course, the type is not just compatible with bool , it is bool .)

+2
source

Here is the juicy part of stdbool.h on my system:

 #define bool _Bool #if __STDC_VERSION__ < 199901L && __GNUC__ < 3 typedef int _Bool; #endif #define false 0 #define true 1 

C99 has a built-in type _Bool and converts all non-zero values ​​to 1 (as was said). However, a quick look at my stdbool.h shows that even in the absence of C99, we can safely assume that this material will work with one caveat that a value that is not equal to zero, or one assigned to _Bool will not be converted to 1 (since _Bool is a simple int typedef, not a built-in type with special properties) and therefore will not == true .

+1
source

All Articles