Should unsigned ints be used if not necessary?

前端 未结 7 1027
醉梦人生
醉梦人生 2020-12-15 05:38

Should one ever declare a variable as an unsigned int if they don\'t require the extra range of values? For example, when declaring the variable in a for loop, if you know i

7条回答
  •  既然无缘
    2020-12-15 06:43

    More often than not, you should use unsigned integers.

    They are more predictable in terms of undefined behavior on overflow and such.
    This is a huge subject of its own, so I won't say much more about it.
    It's a very good reason to avoid signed integers unless you actually need signed values.

    Also, they are easier to work with when range-checking -- you don't have to check for negative values.

    Typical rules of thumb:

    • If you are writing a forward for loop with an index as the control variable, you almost always want unsigned integers. In fact, you almost always want size_t.

    • If you're writing a reverse for loop with an index as a the control variable, you should probably use signed integers, for obvious reasons. Probably ptrdiff_t would do.

    The one thing to be careful with is when casting between signed and unsigned values of different sizes.
    You probably want to double-check (or triple-check) to make sure the cast is working the way you expect.

提交回复
热议问题