49

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

1

1 Answer 1

67

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).

8
  • 5
    Also, one is required to exist and not the other. Feb 16, 2013 at 15:33
  • @user1511417: it makes no sense to ask which is better "a priori" - they both have their use, as outlined in the answer. Feb 16, 2013 at 15:35
  • The uint32_t is also used when exact bit width access is needed, such as writing to hardware registers. Feb 16, 2013 at 17:01
  • uint_least32_t, however, is required to exist. Doesn't help with direct hardware access, but does help with minimum width requirements.
    – DevSolar
    Oct 28, 2015 at 11:59
  • 1
    "0-65535 minimum range" is a slight understatement. It must have a [0, 2^N-1] range with N >=16, in order to support modulo 2^N arithmetic.
    – MSalters
    Oct 28, 2015 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.