Overflow on multiplication of unsigned characters?

When I multiply two unsigned characters in C, like this:

unsigned char a = 200; unsigned char b = 200; unsigned char c = a * b; 

Then I know that I will have an overflow, and I will receive (40'000 modulo 256). 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 is happening with this:

 unsigned char a = 200; unsigned char b = 200; unsigned int c = a * b; 

Can I be sure that the right thing will happen? Is this compiler dependent? Similarly, I do not know what happens when performing the subtraction:

 unsigned char a = 1; unsigned char b = 2; int c = a - b; 

When creating an unsigned "c" char, I will probably get 255. What happens when I use an int like this?

+7
source share
2 answers

The argument of arithmetic operators gets "regular arithmetic promotions."

In cases where int can represent all the values ​​of all operands (in this case, this is an example of your example in most implementations), the arguments are first converted to int. Therefore, in both cases, you get the correct result.

+7
source

Copied from this answer In a C expression, where there are unsigned ints and signed ints, what type will be promoted to what type?

6.3.1.3 Integer and unsigned integers

1 When a value with an integer type is converted to another integer type other than _Bool, if the value can be represented by a new type, it does not change.

2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or> subtracting 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 will be signed and the value cannot be represented in it; either the result> is determined by the implementation, or the signal determined by the implementation rises.

+1
source

All Articles