5

I recently saw someones code that was using this variable type and library on code chef. I was wondering if someone can explain the benefits of using uint32_t as opposed to int, float, double, etc. Also what cases should I use/not use it?

Link to code: http://www.codechef.com/viewsolution/131898

Dolda2000
  • 25,216
  • 4
  • 51
  • 92
user3754017
  • 75
  • 1
  • 7
  • One benefit is portability. Check [uint32_t vs int as a convention for everyday programming](http://stackoverflow.com/questions/20077313/uint32-t-vs-int-as-a-convention-for-everyday-programming). – JosEduSol Sep 10 '14 at 19:23
  • 1
    An aside, not an answer. Since this question is currently marked c++, you really should be using the C++ header, ``, rather the C header ``. – David Hammen Sep 10 '14 at 19:30
  • I use it in embedded systems when I have to access hardware devices that 32 bits wide. This will guarantee that the unsigned integral value will always be 32 bits wide; and the compiler won't shrink it down for something that saves space. – Thomas Matthews Sep 10 '14 at 20:04

1 Answers1

4

The advantage is that a uint32_t is always guaranteed to be 32 bits long, as opposed to the primitive types whose lengths are platform-dependent. For instance, while ints are 32 bits on x86 and x86_64, they are 64 bits on many other 64-bit platforms, and less than that on some older and/or embedded architectures.

One of the cases where it may be beneficial to use a uint32_t, then, could be when you read binary data directly to/from disk/network. You can always just copy 4 bytes into a uint32_t and be sure that it fits. (You'd still have to watch out for eg. differences in endianness, however.)

You may also want to use a uint32_t if you simply want predictable overflow/underflow behavior. Or if you're doing calculations defined in some specific size, like when running some hashing algorithms.

The only thing I have been left wondering is why there aren't corresponding float32_t and float64_t types. :)

Dolda2000
  • 25,216
  • 4
  • 51
  • 92
  • 1
    About float types: [Fixed-size floating point types](http://stackoverflow.com/questions/2524737/fixed-size-floating-point-types) – JosEduSol Sep 10 '14 at 19:31
  • @JosEdu: That answer pretty much just says the obvious, though; that no such typedefs exist in the standard library. – Dolda2000 Sep 10 '14 at 20:05
  • A byte isn't necessarily 8 bits. – T.C. Sep 10 '14 at 21:00
  • While the Standard would in theory allow 32! different storage formats for uint32_t, in practice all systems either store the upper 16 bits followed by the lower 16 bits, or the lower 16 bits followed by the upper 16. I think there should have been optional explicit uint32be_t and uint32le_t types, with defined aliasing for their constituent parts. Code using such types could be more readable and easier to process efficiently than code which tries to assemble everything out of bytes. – supercat Apr 15 '17 at 19:46