Does gcc "forget" the range?
Yes.
It's surprising to me that gcc knows the range of tm_mon, but not surprising that it loses that range once tm_mon is turned into an expression.
In theory gcc could keep tracing through such expressions at compile time, but eventually that becomes equivalent to the halting problem, so stopping as soon as the first + (or -) is encountered seems reasonable to me.
Surprisingly, using 1000 * date_struct->tm_mon does not result in a warning (but should). So this entire warning appears to be half-cooked.
Here is a minimal repro:
#include <stdio.h>
#include <time.h>
#ifndef XXX
#define XXX 0
#endif
void fn(struct tm *date_struct) {
char mm[3]; sprintf (mm, "%02d", date_struct->tm_mon + XXX);
}
gcc --version
gcc (GCC) 14.2.1 20240801 (Red Hat 14.2.1-1)
...
gcc -c -Wall tt.c
# no output
gcc -c -Wall tt.c -DXXX=1
tt.c:9:29: warning: ‘%02d’ directive writing between 2 and 11 bytes into a region of size 3 [-Wformat-overflow=]
9 | char mm[3]; sprintf (mm, "%02d", date_struct->tm_mon + XXX);
| ^~~~
tt.c:9:28: note: directive argument in the range [-2147483647, 2147483647]
9 | char mm[3]; sprintf (mm, "%02d", date_struct->tm_mon + XXX);
| ^~~~~~
tt.c:9:15: note: ‘sprintf’ output between 3 and 12 bytes into a destination of size 3
9 | char mm[3]; sprintf (mm, "%02d", date_struct->tm_mon + XXX);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
struct tm, and treatstm::tm_mon+1as an ordinaryint.