Signed to unsigned conversion in C - is it always safe?

前端 未结 8 1955
北荒
北荒 2020-11-22 01:55

Suppose I have the following C code.

unsigned int u = 1234;
int i = -5678;

unsigned int result = u + i;

What implicit conversions are goin

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 02:50

    What implicit conversions are going on here,

    i will be converted to an unsigned integer.

    and is this code safe for all values of u and i?

    Safe in the sense of being well-defined yes (see https://stackoverflow.com/a/50632/5083516 ).

    The rules are written in typically hard to read standards-speak but essentially whatever representation was used in the signed integer the unsigned integer will contain a 2's complement representation of the number.

    Addition, subtraction and multiplication will work correctly on these numbers resulting in another unsigned integer containing a twos complement number representing the "real result".

    division and casting to larger unsigned integer types will have well-defined results but those results will not be 2's complement representations of the "real result".

    (Safe, in the sense that even though result in this example will overflow to some huge positive number, I could cast it back to an int and get the real result.)

    While conversions from signed to unsigned are defined by the standard the reverse is implementation-defined both gcc and msvc define the conversion such that you will get the "real result" when converting a 2's complement number stored in an unsigned integer back to a signed integer. I expect you will only find any other behaviour on obscure systems that don't use 2's complement for signed integers.

    https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation https://msdn.microsoft.com/en-us/library/0eex498h.aspx

提交回复
热议问题