Typecast for unsigned char and multiply variables

printf("%d\n", (unsigned char)255 * (unsigned char)255); 

The output code above is 65025, but not 1 (255 * 255 (mod 256)). Why?

+6
source share
2 answers

The multiplication operator * applies regular arithmetic conversions to its operands. These conversions convert unsigned char operands to int . See pmg answer for a standard link.

Obviously your int system type is wide enough to hold the result value of 65025 . On a system with a 16-bit int , where INT_MAX == 32767 , multiplication will overflow, causing undefined behavior (as a rule, the most significant bits of the result will be discarded). Most modern systems have a 32-bit int .

There is no multiplication operator for integer types narrower than int or unsigned int .

(Strictly speaking, it is possible that operands can be converted to unsigned int , but not to int . This will only happen if unsigned int can represent the entire range of unsigned char , but int cannot - and this cannot happen in the system with 8 bit char .)

+13
source

The operands * undergo the usual arithmetic transformations (C11 Standard p6.3.1.8).

Also see p6.5.5.2: Multiplicative operators

Semantics
Normal arithmetic conversions are performed on operands.

+6
source

Source: https://habr.com/ru/post/988738/


All Articles