When I multiply two unsigned chars in C like this:
unsigned char a = 200;
unsigned char b = 200;
unsigned char c = a * b;
Then I know I will have an overflow, and I get (40'000 modulo 256) as a result. When I do this:
unsigned char a = 200;
unsigned char b = 200;
unsigned int c = (int)a * (int)b;
I will get the correct result 40'000. However, I do not know what happens with this:
unsigned char a = 200;
unsigned char b = 200;
unsigned int c = a * b;
Can I be sure the right thing happens? Is this compiler dependent? Similarly, I don't know what happens when doing a subtraction:
unsigned char a = 1;
unsigned char b = 2;
int c = a - b;
When making "c" an unsigned char, I will probably get 255 as a result. What happens when I use an int like this?
We can multiply recursively to overcome the difficulty of overflow. To multiply a*b, first calculate a*b/2 then add it twice. For calculating a*b/2 calculate a*b/4 and so on (similar to log n exponentiation algorithm).
However, since i is an unsigned char, it is rerepsented by an 8-bit value which, after reaching 255, will overflow (so it will go back to 0) and the loop will therefore go on forever.
A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
The electronic circuits of a processor can easily detect overflow of unsigned binary addition by checking if the carry-out of the leftmost column is a zero or a one. A program might branch to an error handling routine when overflow is detected.
Argument of arithmetic operators get the "usual arithmetic promotions".
In cases where int can represent all the values of all the operands (at it is the case for your example in most implementations), arguments are first converted to int. So in both cases, you get the correct result.
Copied from this answer In a C expression where unsigned int and signed int are present, which type will be promoted to what type?
6.3.1.3 Signed and unsigned integers
1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or >subtracting one more than the maximum value that can be represented in the new type until the >value is in the range of the new type.
3 Otherwise, the new type is signed and the value cannot be represented in it; either the >result is implementation-defined or an implementation-defined signal is raised.
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