printf("%d\n", (unsigned char)255 * (unsigned char)255);
The output of the code above is 65025 but not 1 (255 * 255 (mod 256)). Why?
The multiplication operator *
applies the usual arithmetic conversions to its operands. These conversions convert the unsigned
char operands to int
. See pmg's answer for the standard reference.
Apparently on your system type int
is wide enough to hold the result value 65025
. On a system with 16-bit int
, where INT_MAX == 32767
, the multiplication would result in an overflow, causing undefined behavior (typically the high-order bits of the result would be discarded). Most modern systems have 32-bit int
.
There is no multiplication operator for integer types narrower than int
or unsigned int
.
(Strictly speaking, it's possible that the operands could be converted to unsigned int
rather than to int
. That would happen only if unsigned int
can represent the entire range of unsigned char
, but int
cannot -- and that cannot happen on a system with 8-bit char
.)
The operands to *
undergo the "usual arithmetic conversions" (C11 Standard p6.3.1.8).
Also see p6.5.5.2: Multiplicative operators
Semantics
The usual arithmetic conversions are performed on the operands.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With