Reputation: 11
What is the difference between the following two?
// uint8_t a; uint8_t b;
uint16_t first = (uint16_t)(a * b);
uint16_t second = (uint16_t)a * (uint16_t)b;
What could be the use cases of these two kinds of implementations?
Upvotes: 1
Views: 47
Reputation: 154166
The mathematical product of a*b
is in the range [0...65,025].
If unsigned/int
is 32-bit, no difference.
If unsigned/int
is 16-bit, a * b
risks signed int
overflow and undefined behavior (UB). Both a, b
are converted to int
prior to the multiplication and a*b
may exceed INT_MAX
(32,767).
(uint16_t)a * (uint16_t)b;
is better.
Upvotes: 2