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

问题描述 投票:2回答:1

我正在使用带有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);
                        ^
c compiler-warnings gcc-warning
1个回答
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


如果代码转换为unsignedfor 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);

故事的道德:使用匹配的打印说明符和每个参数。

© www.soinside.com 2019 - 2024. All rights reserved.