c - C99: Equality operator expression to bool conversion warning
问题描述
I am compiling the following code using WindRiver Diab for Power PC, a proprietary C99 compiler for embedded systems:
#include <stdbool.h>
bool foo(int a, int b)
{
return a == b; /* int to unsigned char conversion */
}
I had expected this code to compile without warnings, but is no, the compiler reports:
warning: ... signed-to-unsigned type conversion found: int to unsigned char
On one hand, as the the type of the equality operator expression is int
and the type of bool
(in this case) is apparently unsigned char
, the warning seems to make sense. On the other hand, the code looks pretty standard. Shouldn't it compile without warnings? What is the standard saying?
解决方案
A warning is proper, but pedantic. The result of ==
is certainly int
(C 1999, §6.5.9 ¶3). And _Bool
(what bool
expands into) is one of the standard unsigned integer types (C 1999, §6.2.5 ¶6). Of course, bool
expands to _Bool
(C 1999, §7.16 ¶2).
However, since the result of ==
is either 0 or 1, the compiler could deduce it will not suffer any ill effects from the conversion, and the warning could have been suppressed. In particular, conversion to _Bool
is well defined to be either 0 or 1 (C 1999, §6.3.1.2 ¶1).
The warning shown in the question does not mention conversion to bool
or _Bool
, but instead mentions unsigned char
. This seems out of place, and is another indication that the quality of the compiler could be improved.†</sup>
For comparison, GCC requires -Wconversion
be added specifically to get these conversion warnings. Even with the flag, GCC does not generate any warning when converting result of ==
to unsigned
. And, it does not generate any warning for any arithmetic conversion (including negative values) to _Bool
.
†<sub>Keith Thompson notes in a comment that _Bool
and unsigned char
are distinct types in C and cannot be treated as compatible types.