我正在使用带有ARM Cortex A9的GCC 5.2.1,并使用-std = c11和-Wformat-signness进行编译。
在这种情况下如何避免-Wformat警告?
int main()
{
enum
{
A = 0,
B
};
char buff[100];
snprintf(buff, 100, "Value is 0x%04x\n", A);
return 0;
}
这会产生警告:
format '%x' expects argument of type 'unsigned int', but argument 4 has
type 'int' [-Werror=format=]
snprintf(buff, 100, "Value is 0x%04x\n", A);
^
显式强制转换会产生相同的结果:
format '%x' expects argument of type 'unsigned int', but argument 4 has
type 'int' [-Werror=format=]
snprintf(buff, 100, "Value is 0x%04x\n", (uint16_t)A);
^
答案 0 :(得分:3)
在这种情况下,如何避免-Wformat警告?
将枚举类型设置为unsigned
以匹配"%x"
。
// snprintf(buff, 100, "Value is 0x%04x\n", A);
snprintf(buff, 100, "Value is 0x%04x\n", (unsigned) A);
o,u,x,X
unsigned int
参数转换为... C11§7.21.6.18
如果代码强制转换为unsigned
,for some reason以外的内容,请使用指定的匹配打印说明符。 @Chrono Kitsune
#include <inttypes.h>
// snprintf(buff, 100, "Value is 0x%04x\n", (uint16_t)A);
snprintf(buff, 100, "Value is 0x%04" PRIX16 "\n", (uint16_t)A);
如果故事是道德的:对每个参数使用匹配的打印说明符。