【发布时间】:2021-05-14 08:36:06
【问题描述】:
我正在使用 WindRiver Diab for Power PC(一种用于嵌入式系统的专有 C99 编译器)编译以下代码:
#include <stdbool.h>
bool foo(int a, int b)
{
return a == b; /* int to unsigned char conversion */
}
我原以为这段代码编译时不会出现警告,但不是,编译器报告:
警告:...找到有符号到无符号的类型转换:int 到无符号字符
一方面,由于相等运算符表达式的类型是int,而bool(在这种情况下)的类型显然是unsigned char,因此警告似乎是有道理的。另一方面,代码看起来很标准。它不应该在没有警告的情况下编译吗?标准的说法是什么?
【问题讨论】:
-
你能分享一下它是什么编译器吗?
without warnings警告是编译器的内部内容,它是特定编译器的实现质量。所以Shouldn't it compile without warnings? What is the standard saying?标准没有提到任何警告,也不关心警告。 -
至于解决它,您可以尝试
return x;,因为== true是多余的。或者你可以试试return (bool) (x == true);。或者您可以禁用该警告。您还应该向供应商写一封投诉信。 -
值得一提的是,包含
<stdbool.h>,根据标准,应该导致bool扩展为_Bool而不是unsigned char,所以看起来编译器不符合C99 标准。 -
请注意,即使 bool 表示为 unsigned char,从 int 到 bool 的转换不与从 int 到 unsigned char 的转换相同。它被 C99 标准定义为将任何比较等于 0 的值转换为 false,将其他所有值转换为 true。
-
@AndrewHenle 为什么不两者兼而有之?
标签: c type-conversion language-lawyer c99