Apologies, I didn't realize that my mail client doesn't
auto-wrap. Please find a wrapped copy of my original message below my
signature.

-Ani

On Thu, Jun 16, 2022, at 9:11 PM, Aniruddh Agarwal wrote:
> Hello,
>
> A colleague patched a prod-critical bug today caused by an overlooked 
> implicit int promotion when adding uint8_t's. g++  (v12.1) doesn't 
> report any warnings for it with all combinations of warnings flags that 
> I've tried, so I thought I'd ask if:
>
> - there *is* already some combination of warning flags that *would* 
> report a warning for this code
>
> - if not, then if there's any interest in work (which of course I'd be 
> happy to contribute to) on detecting and flagging this sort of problem. 
>
> A (much simplified) example which illustrates the bug:
> #+BEGIN_SRC cpp
> #include <cstdint>
>
> using std::uint8_t;
>
> bool foo(uint8_t a, uint8_t b, uint8_t c) {
>     return (a + b) == c;
> }
> #+END_SRC
>
> Here's the problem: the expectation here is that "a + b" will have type 
> uint8_t. So, for example it expects "foo(200, 200, 144)" to return 
> "true".
>
> In reality, "a + b" implicitly promotes to an "int" and so we end up 
> comparing 400 and 144, which returns false.
>
> (Side note, not immediately relevant: I'm not sure if this ends up 
> being equivalent to calling something like a "bool operator==(int, 
> uint8_t)" or if the RHS is also implicitly promoted to an int before 
> the comparison. This is irrelevant for the immediate example because 
> the end result is the same in either case, but I would appreciate it if 
> someone can shed light on what the standard has to say on this for 
> future reference.)
>
> A correct implementation of the expected behavior is instead therefore:
> #+BEGIN_SRC cpp
> #include <cstdint>
>
> using std::uint8_t;
>
> bool foo(uint8_t a, uint8_t b, uint8_t c) {
>     return static_cast<uint8_t>(a + b) == c;
> }
> #+END_SRC
>
> Does anyone else find this very surprising, and as I asked above, does 
> it seem worthwhile to try to flag code like in the first snippet? I 
> don't know what gcc's general policy on trying to warn about code like 
> this is. The new theoretical  warning would be in the spirit of 
> -Wconversion.
>
> -Ani

Reply via email to