[Solved] Is there a difference between these two operations? [closed]


These statements do not generally have the same behavior as defined by the C standard. Consider when s16X has the least value of its type (e.g., perhaps INT_MIN in an implementation where the int type is 16 bits, so it could be −32767) and s16Y is 2. Then, in:

s16Result = (T_S16) (s16X - s16Y)

the expression s16X - s16Y overflows—the mathematical result of −32769 is not representable in the int type, and the C standard does not define the result.

However, in:

s16Result = (T_S16) ((T_U16) s16X - (T_U16) s16Y)

the T_U16 type is presumably an unsigned 16-bit type. In this case, s16X is converted to the 16-bit type by adding or subtracting 65536, yielding 32769. s16Y retains its value of 2. Then the subtraction yields 32767. finally, this result is converted to the T_S16 type, which keeps the value 32767.

Thus, the statement with unsigned arithmetic may have a defined value in some situations where the statement with signed arithmetic does not have a value defined by the C standard.

(The statement with unsigned arithmetic still has undefined behavior if the final result is not representable in the T_S16 type, as when the final result is a number from 32768 to 65535 rather than from 0 to 32767.)

solved Is there a difference between these two operations? [closed]