On Wed, 8 May 2024 at 16:47, Linus Torvalds <torva...@linux-foundation.org> wrote: > > So *that* I feel could be something where you can warn without a ton > of compiler smarts at all. If you see an *implicit* cast to unsigned > and then the subsequent operations wraps around, it's probably worth > being a lot more worried about.
Side note on this part: quite often, because of C promotion rules, you have "int" as an "intermediate" type. IOW, while I had that example of int a; ... a * sizeof(xyz); being questionably not-UB (because "int a" gets promoted to unsigned as part of C integer promotion, and thus you really had a signed value that was involved in unsigned wrap-around), if you have unsigned short a; ... a * sizeof(xyz); then technically that 'a' is first promoted to 'int' (because all arithmetic on types smaller than int get promoted to int), and then it gets promoted to size_t because the multiply gets done in the bigger type. So in one sense that unsigned multiply may actually have involved a cast from a signed type, but at the same time it's not at all in that kind of "accidentally not UB" class. I suspect most compilers would have combined the two levels of implicit casts into just one, so at no point outside of perhaps some very intermediate stage will it show as a signed int cast to unsigned, but I thought I'd mention it anyway. Implicit casts get nasty not just in assignments, but also in these kinds of situations. I still suspect the "implicit truncating cast at assignment" is likely a much more common case of loss of information than actual arithmetic wrap-around, but clearly the two have commonalities. Linus