Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate warnings for incorrect sign with printf format specifier

Tags:

c

gcc-warning

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.

like image 653
Brian Stormont Avatar asked Oct 13 '16 17:10

Brian Stormont


Video Answer


1 Answers

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;

like image 137
2501 Avatar answered Oct 01 '22 13:10

2501