Search code examples
c++cintsizeint32

How does uint32_t guarantee 32 bits?


In most implementations, I've seen uint32_t defined as

typedef unsigned int uint32_t;

But as I understand it ints are not always guaranteed to be 4 bytes across all systems. So if the system has non 4-byte integers, how does uint32_t guarantee 4?


Solution

  • An implementation is required to define uint32_t correctly (or not at all if that's not possible).

    If unsigned int meets the requirements (32 bits wide, no padding bits), the implementation can define it as

    typedef unsigned int uint32_t;
    

    If it doesn't, but unsigned long does meet the requirements, it can define it as:

    typedef unsigned long uint32_t;
    

    Or it can use a different unsigned type if that's appropriate.

    The <stdint.h> header has to be compatible with the compiler that it's used with. If you took a <stdint.h> header that unconditionally defined uint32_t as unsigned int, and used it with a compiler that makes unsigned int 16 bits, the result would be a non-conforming implementation.

    Compatibility can be maintained either by tailoring the header to the compiler, or by writing the header so that it adapts to the characteristics of the compiler.

    As a programmer, you don't have to worry about how correctness is maintained (though of course there's nothing wrong with being curious). You can rely on it being done correctly -- or you can complain to the provider about a serious bug.