Don't shoot your foot: Integer promotion edition
Mark Kirichenko
SDE @AWS EC2 Accelerated Nitro | Security Guardian | C++ | Embedded | FW | HW | RTOS
In my previous post I've talked about signed integer overflows, how do they happen, and why are they so dangerous.
However, the problem is, that sometimes these overflows are come from an unexpected source. To get the idea, please take a look at the following code:
unsigned short a = 0xFFFF;
unsigned short b = 0xFFFF;
auto c = a * b;
If you can't see Undefined Behaviour here, it doesn't mean there isn't. In fact, this code has the same problem of signed integer overflow, but now it's happening because of an amazingly annoying mechanism: integer promotion.
The need for integer promotions originates from the fact that operations on numbers (addition, subtraction, multiplication, division) are not defined for all the numeric types. For example, unsigned short is one of these types. In order to make mathematical operations possible, numbers are promoted.
In general, it looks like this:
More details can be found on cppreference.com.
So, my recommendations are: