|
|
|
|
|
by nayuki
65 days ago
|
|
Thank you for being one of the few people who understands that in C/C++, `unsigned OP unsigned` can have each operand be promoted to a signed integer and then have the operation overflow and cause undefined behavior. I chose to deal with this problem by doing a "pointless" operation to force a promotion to at least unsigned int. For example: uint16_t x = 0xFFFF;
uint16_t y = 0xFFFF;
uint16_t z = (uint16_t)((x + 0U) * (y + 0U));
This piece of code will work on any machine, such as: (uint16_t = unsigned short = 16 bits, uint32_t = unsigned int = 32 bits); (uint16_t = unsigned short = unsigned int = 16 bits, uint32_t = unsigned long = 32 bits). |
|