espression with unsigned and signed


I recently researched that it is better to avoid the use of expressions that mix signed and unsigned types because they can give us back unexpected results ...... examples if int a = -1; unsigned int b = 1; a * b = 4294967295

why if a is a long long type that does not work? because the result is -1 and not the maximum value storable in a long long type as it should be ?

Last edited on
11111111 11111111 11111111 11111111 * 00000000 00000000 00000000 00000001 = 11111111 11111111 11111111 11111111 (unsigned) = ~0 (unsigned) = U_MAX
Well, the result should be the same.
I think this topic needs to be considered in the context of type promotion.

For example where one operand is of type float and the other is double, the float is converted to a double before the operation. Similarly with short and long for example. But rather than depending upon these automatic conversions, it is sometimes better to specify which conversion you want to take place.

The same issues can arise say when one variable is a floating-point type and the other is an integer. The default would usually be to make both operands floating point before the operation, but that may not always be what is required.

http://www.cplusplus.com/doc/tutorial/typecasting/
http://stackoverflow.com/questions/5563000/implicit-type-conversion-rules-in-c-operators
Topic archived. No new replies allowed.