What is the difference between an Uint32 and an unsigned int in C++?

Is it the same? If no: what is the difference? If yes then why do you need this type?


Solution 1:

uint32_t (or however pre-C++11 compilers call it) is guaranteed to be a 32-bit unsigned integer; unsigned int is whatever unsigned integer the compiler likes best to call unsigned int, as far as it meets the requirements of the standard (which demands for it a 0-65535 minimum range).

Like int, unsigned int typically is an integer that is fast to manipulate for the current architecture (normally it fits into a register), so it's to be used when a "normal", fast integer is required.

uint32_t, instead, is used when you need an exact-width integer, e.g. to serialize to file, or when you require that exact range or you rely on unsigned overflow to happen exactly at 2^32-1.

For example, on a 16 bit-processor unsigned int will typically be 16 bits wide, while uint32_t will have to be 32 bits wide.


Incidentally, as pointed out by @Marc Glisse, while unsigned int is always present, uint32_t is not mandatory - a particular compiler implementation may not provide it. This is mostly because not all platforms can easily provide such a type (typically DSPs with weird word sizes).