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

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

    As was previously answered, you can cast back and forth between signed and unsigned without a problem. The border case for signed integers is -1 (0xFFFFFFFF). Try adding and subtracting from that and you'll find that you can cast back and have it be correct.

    However, if you are going to be casting back and forth, I would strongly advise naming your variables such that it is clear what type they are, eg:

    int iValue, iResult;
    unsigned int uValue, uResult;
    

    It is far too easy to get distracted by more important issues and forget which variable is what type if they are named without a hint. You don't want to cast to an unsigned and then use that as an array index.

提交回复
热议问题