About the use of signed integers in C family of languages

后端 未结 5 1012
一整个雨季
一整个雨季 2021-01-11 17:57

When using integer values in my own code, I always try to consider the signedness, asking myself if the integer should be signed or unsigned.

When I\'m sure the valu

5条回答
  •  醉梦人生
    2021-01-11 18:41

    There is one heavy-weight argument against widely unsigned integers:

    Premature optimization is the root of all evil.

    We all have at least on one occasion been bitten by unsigned integers. Sometimes like in your loop, sometimes in other contexts. Unsigned integers add a hazard, even though a small one, to your program. And you are introducing this hazard to change the meaning of one bit. One little, tiny, insignificant-but-for-its-sign-meaning bit. On the other hand, the integers we work with in bread and butter applications are often far below the range of integers, more in the order of 10^1 than 10^7. Thus, the different range of unsigned integers is in the vast majority of cases not needed. And when it's needed, it is quite likely that this extra bit won't cut it (when 31 is too little, 32 is rarely enough) and you'll need a wider or an arbitrary-wide integer anyway. The pragmatic approach in these cases is to just use the signed integer and spare yourself the occasional underflow bug. Your time as a programmer can be put to much better use.

提交回复
热议问题