开发者

overflow when multiplying unsigned chars?

开发者 https://www.devze.com 2023-03-11 11:18 出处:网络
When I multiply two unsigned chars in C like this: u开发者_如何学Cnsigned char a = 200; unsigned char b = 200;

When I multiply two unsigned chars in C like this:

u开发者_如何学Cnsigned 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消