Reputation: 3069
I vaguely know that the return type of a Boolean operator is int
in C, but is it guaranteed to be the unflavored int
, and not, say, unsigned int
?
I am generally concerned if I am allowed to negate the result of a Boolean operation and expect it to be either 0
or -1
, and not 2^32 - 1
. See the following example:
int main(void) {
int a = -(5 == 5);
// Is "a" guaranteed to be -1 here?
}
Upvotes: 2
Views: 81
Reputation: 5265
The result of a comparison and logical operators is the value 0
or 1
of type int
. int
is specified to hold at least the integer range [−32,767, +32,767].
-(5 == 5)
is therefore always -1
, and -(5 == 4)
is 0
,
Doing this is however confusing. The results of these operators is usually treated in a boolean-like way, and using the numerical value of the result might make it harder to understand the code.
Using the ternary operator may make the intent more clear:
(5 == num) ? -1 : 0
Using a number of compilers on the Compiler Explorer, I didn't see a difference in the generated code.
Upvotes: 3