Why is int rather than unsigned int used for C and C++ for loops?

后端 未结 10 2095
日久生厌
日久生厌 2020-12-02 15:50

This is a rather silly question but why is int commonly used instead of unsigned int when defining a for loop for an array in C or C++?

<         


        
10条回答
  •  感动是毒
    2020-12-02 16:20

    Aside from the issue that it's shorter to type, the reason is that it allows negative numbers.

    Since we can't say in advance whether a value can ever be negative, most functions that take integer arguments take the signed variety. Since most functions use signed integers, it is often less work to use signed integers for things like loops. Otherwise, you have the potential of having to add a bunch of typecasts.

    As we move to 64-bit platforms, the unsigned range of a signed integer should be more than enough for most purposes. In these cases, there's not much reason not to use a signed integer.

提交回复
热议问题