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

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

    When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

    So it is safe in the sense of that the result might be huge and wrong, but it will never crash.

提交回复
热议问题