Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros and cons of int, unsigned int, uint_fastN_t, and int_fastN_t?

I have a variable and the type does not matter; the possible range will easily fit in any of the aforementioned types. For example a loop counter. Etc.

What are the pros and cons of using:

  • int
  • unsigned int
  • int_fastN_t
  • uint_fastN_t

Note to any potential close-voters: I am not asking which ones to use, because that would be opinion-based, but I am asking, what factors should I consider when choosing one over the other?

like image 539
user22200698 Avatar asked Dec 12 '25 16:12

user22200698


1 Answers

Signed vs. Unsigned

  • Prefer unsigned types for logical and pattern data manipulation.

  • If following a documented algorithm, match its sign-ness should it specify one.

  • Use signed types for general data manipulation.

  • Avoid mixing sign-ness of types in an equation.

  • Use size_t (an unsigned type) for array sizing and indexing.

  • Operations with signed types readily incur UB @Lundin thus unsigned types are favored in critical applications.

Fast or not

  • Avoid (u)int_fastN_t unless certain of the need. Maybe when a narrow type is needed, yet speed it critical. They are not worth using on a whim.

  • fast types oblige documentation to justify it use.

  • Never use ...fast.. as a bit-field.

  • Wide (u)int_fastN_t is rarely useful.

  • Portability: (u)int_fastN_t/(u)int_leastN_t are always available since C99 and have a slight edge concerning portability versus the optional (u)intN_t.
    int/unsigned are always available since the dawn of C.

  • Keep in mind that fast types are a compromise. Fast is not always fastest in all use cases.

like image 178
chux - Reinstate Monica Avatar answered Dec 14 '25 10:12

chux - Reinstate Monica