printf 中整数提升的 C -Wformat 警告

C -Wformat warning for integer promotion in printf

我正在使用带有 ARM Cortex A9 的 GCC 5.2.1,并使用 -std=c11 和 -Wformat-signedness 进行编译。

在这种情况下如何避免出现 -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);
                        ^

How do I avoid a -Wformat warning in this case?

将枚举类型转换为 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 The unsigned int argument is converted to ... C11 §7.21.6.1 8


如果代码强制转换为 unsigned 以外的内容,, use the specified matching print specifier.

#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);

故事的寓意:对每个参数使用匹配的打印说明符。