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

前端 未结 8 1954
北荒
北荒 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:47

    Referring to the bible:

    • Your addition operation causes the int to be converted to an unsigned int.
    • Assuming two's complement representation and equally sized types, the bit pattern does not change.
    • Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)
    • The rules are a little more complicated in the case of combining signed and unsigned of differing sizes.

提交回复
热议问题