https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128708
Bug ID: 128708
Summary: wrong code with -fprintf-return-value: "%.0hd" /
"%.hhx" of a constant that is zero only after
narrowing is counted as one digit
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: 0599jiangyc at gmail dot com
Target Milestone: ---
The following code:
```c
/* -fprintf-return-value: "%.0hd"/"%.0hhd"/"%.hx" with a constant argument that
becomes 0 only
after conversion to the directive's type (short/char) is counted as 1 byte
instead of 0.
Godbolt: x86-64 gcc (trunk), flags: -O2
gcc -O1 repro.c && ./a.out (also -O2, -O3; fixed by
-fno-printf-return-value)
Expected: exit 0. GCC trunk (and 11): "FAIL", exit 1. */
#include <stdio.h>
__attribute__((noipa)) int
f (char *b)
{
int v = 0x10000; /* (short) v == 0 */
return sprintf (b, "%.0hd", v); /* prints nothing -> 0; folded to 1 */
}
__attribute__((noipa)) int
g (void)
{
return snprintf (0, 0, "[%.hhx]", 256); /* "[]" -> 2; folded to 3 */
}
int
main (void)
{
char b[16];
int bad = 0;
if (f (b) != 0)
bad |= 1;
if (g () != 2)
bad |= 2;
if (bad)
{
printf ("FAIL %d\n", bad);
return 1;
}
printf ("OK\n");
return 0;
}
```
Resulted in this output:
```
$ gcc -O2 repro.c && ./a.out
FAIL 3
(gcc -O0, -O2 -fno-printf-return-value and clang print OK)
```
Trunk: https://godbolt.org/z/nsfTvWajr (x86-64 gcc trunk, -O2, executed;
reproduces as of 2026-11-13; also GCC 14.2 and GCC 11)
Root cause: gcc/gimple-ssa-sprintf.cc, format_integer (), INTEGER_CST argument:
```
if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
{ /* zero precision and zero value: no output */ }
else
{
arg = fold_convert (dirtype, arg);
res.range.min = tree_digits (arg, base, dir.prec[0], ...);
```
The zero test is done on the argument before it is converted to the directive's
type (short for h, char for hh). A constant such as 0x10000 or 256, or INT_MIN
for %hd, is zero after the conversion and prints nothing, but it misses the
special case. tree_digits then counts one digit. sprintf (b, "%.0hd", 0x10000)
is folded to 1 although it returns 0, and snprintf (0, 0, "[%.hhx]", 256) is
folded to 3 although it returns 2. PR78606 fixed the zero-value rules but not
the narrowing case.
Suggested fix: perform fold_convert (dirtype, arg) before the integer_zerop
test.