Why do we use signed integers for loops?

Indexes are always non-negative, so I use size_twhere possible. Why is it usually to use signed integers? What is the reason for this?

+4
source share
3 answers

I think this is mainly due to several reasons that work together:

  • History, I think, intwas mostly considered a “machine word” that day (and probably, after all, by many). So this is a kind of "default type", one that you use without further thought.
  • Many loops are short, so the best precision given by unsigned types doesn't matter, which is why people don't think about using an unsigned type.
  • Ease of input, intmuch more comfortable on hand than unsignedor ( unsigned int).
  • Many people simply do not understand how sensitive the unsigned type is for iteration, or (horror) do not care.
+3
source

If you mean things like

for(int i=0; i<n; i++)

then there is no rationale. Sloppy, lazy programmers write sloppy code, just like that.

, . size_t, . uint_fastn_t, "n" , .

+1

0, , , . :

for (int i = n - 1; i >= 0; i--) {
    ...
}

. , :

for (unsigned i = n; i-- > 0; ) {
    ...
}

, unsigned: C, , .

The reason for the widespread use intis historical: it size_twas introduced at the end of the game and only became larger than unsignedrecently, with the exception of some older exotic systems.

0
source

Source: https://habr.com/ru/post/1656943/


All Articles