Search code examples
cgcc-warning

Generate warnings for incorrect sign with printf format specifier


Is there any way to get gcc or clang to generate warnings for a mismatch with signed vs. unsigned variables with the printf() format specifiers?

I am aware of using -Wformat, however that only reports a warning if the size of the data type is incorrect. It will not generate a warning if only the sign is incorrect.

For example the following does not generate a warning even though there is a mismatch with printing an unsigned int as signed:

uint32_t x = UINT_MAX;
printf("%d", x);

This will print out -1.

It seems like this would be a useful warning, but I haven't found any way to enable it.


Solution

  • Use: -Wformat along with -Wformat-signedness (-Wformat must be present).

    The latter warning option will warn if the argument is of incorrect signedness for the printf specifier.

    gcc 6.2 will produce this warning: warning: format '%d' expects argument of type 'int', but argument 2 has type 'uint32_t {aka unsigned int}' [-Wformat=]

    Also uint32_t x = UINT_MAX; should be uint32_t x = UINT32_MAX;