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

后端 未结 10 2097
日久生厌
日久生厌 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:03

    It's purely laziness and ignorance. You should always use the right types for indices, and unless you have further information that restricts the range of possible indices, size_t is the right type.

    Of course if the dimension was read from a single-byte field in a file, then you know it's in the range 0-255, and int would be a perfectly reasonable index type. Likewise, int would be okay if you're looping a fixed number of times, like 0 to 99. But there's still another reason not to use int: if you use i%2 in your loop body to treat even/odd indices differently, i%2 is a lot more expensive when i is signed than when i is unsigned...

提交回复
热议问题