Why would uint32_t be preferred rather than uint_fast32_t?

前端 未结 11 1158
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 00:58

It seems that uint32_t is much more prevalent than uint_fast32_t (I realise this is anecdotal evidence). That seems counter-intuitive to me, though.

11条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 01:49

    Why do many people use uint32_t rather than uint32_fast_t?

    Note: Mis-named uint32_fast_t should be uint_fast32_t.

    uint32_t has a tighter specification than uint_fast32_t and so makes for more consistent functionality.


    uint32_t pros:

    • Various algorithms specify this type. IMO - best reason to use.
    • Exact width and range known.
    • Arrays of this type incur no waste.
    • unsigned integer math with its overflow is more predictable.
    • Closer match in range and math of other languages' 32-bit types.
    • Never padded.

    uint32_t cons:

    • Not always available (yet this is rare in 2018).
      E.g.: Platforms lacking 8/16/32-bit integers (9/18/36-bit, others).
      E.g.: Platforms using non-2's complement. old 2200

    uint_fast32_t pros:

    • Always available.
      This always allow all platforms, new and old, to use fast/minimum types.
    • "Fastest" type that support 32-bit range.

    uint_fast32_t cons:

    • Range is only minimally known. Example, it could be a 64-bit type.
    • Arrays of this type may be wasteful in memory.
    • All answers (mine too at first), the post and comments used the wrong name uint32_fast_t. Looks like many just don't need and use this type. We didn't even use the right name!
    • Padding possible - (rare).
    • In select cases, the "fastest" type may really be another type. So uint_fast32_t is only a 1st order approximation.

    In the end, what is best depends on the coding goal. Unless coding for very wide portability or some niched performance function, use uint32_t.


    There is another issue when using these types that comes into play: their rank compared to int/unsigned

    Presumably uint_fastN_t could be the rank of unsigned. This is not specified, but a certain and testable condition.

    Thus, uintN_t is more likely than uint_fastN_t to be narrower the unsigned. This means that code that uses uintN_t math is more likely subject to integer promotions than uint_fastN_t when concerning portability.

    With this concern: portability advantage uint_fastN_t with select math operations.


    Side note about int32_t rather than int_fast32_t: On rare machines, INT_FAST32_MIN may be -2,147,483,647 and not -2,147,483,648. The larger point: (u)intN_t types are tightly specified and lead to portable code.

提交回复
热议问题