Consider the following example:
unsigned short c = // ...
if (c > 0xfffful)
c = 0xfffful;
Since unsigned short
can actually be larger than 16 bits, I want to limit the value before snprintf
it in hex format to a fixed-size buffer.
However, GCC (but not clang) gives a warning: comparison is always false due to limited range of data type [-Wtype-limits]
.
Is it a bug in GCC or I missed something? I understand that on my machine unsigned short
is exactly 16 bits, but it's not guaranteed to be so on other platforms.
I'd say it is not a bug. GCC is claiming if (c > 0xfffful)
will always be false, which, on your machine, is true. GCC was smart enough to catch this, clang wasn't. Good job GCC!
On the other hand, GCC was not smart enough to notice that while it was always false on your machine, its not necessarily always false on someone else's machine. Come on GCC!
Note that in C++11, the *_least##_t
types appear (I reserve the right to be proven wrong!) to be implemented by typedef. By the time GCC is running it's warning checks it likely has no clue that the original data type was uint_least16_t
. If that is the case, the compiler would have no way of inferring that the comparison might be true on other systems. Changing GCC to remember what the original data type was might be extremely difficult. I'm not defending GCC's naive warning but suggesting why it might be hard to fix.
I'd be curious to see what the GCC guys say about this. Have you considered filing an issue with them?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With