Search code examples
c++fixed-width

C++: Disadvatages of using std::uint_fastn_t


So I stumbled upon When should I use the C++ fixed-width integer types and how do they impact performance? and Should I use cstdint? where the advantages and disadvantages of fixed width integer types as defined in <cstdint> are listed.

I kinda do like to encode the intended range of a variable into its type but I also don't want to enforce the CPU to do extra operations just to use a uint16_t instead of a plain int when I am not strictly required to have a variable holding exactly 16 bits.

I also read about types like std::uint_fast16_t and so on. From my understanding using this type should ensure that I am guaranteed to be able to store a 16-bit number in that variable but I should never have to pay any runtime penality for using this type since on every architecture where e.g. uint32_t would be faster, that would be used automatically for me.

This leaves me with the question: Aside from the case that I really need a variable of exact bit width, are there any disadvantages of using std::uint_fast16_t instead of say unsigned int?


EDIT: This is of course assuming that memory consumption is not an issue. If it was, I would use std::uint_least16_t instead.


Solution

  • are there any disadvantages of using std::uint_fast16_t instead of say unsigned int.

    One disadvantage: uncertain type due do the usual promotions. Does uint16_fast_t convert to a signed or unsigned?

    uint_fast16_t fa = 1;
    unsigned un = 1;
    int i;
    
    fa some_operator i --> may result in an `int` or `uint_fast16_t`
    un some_operator i --> result is unsigned.
    

    The ambiguity may negatively affect more complicated equations and behavior on overflow.


    IMO, uint16_fast_t only useful in narrow controlled code, not for a general performance improvement. Be careful of Is premature optimization really the root of all evil?.

    Many factors affect this conclusion, yet generally for performance, usually best to go for clarity and type unsigned.