Reputation: 20129
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?
Upvotes: 3
Views: 2834
Reputation: 222650
Each C or C++ implementation that defines uint32_t
defines it in a way that works for that implementation. It may use typedef unsigned int uint32_t;
only if unsigned int
is satisfactory for uint32_t
in that implementation.
The fact that typedef unsigned int uint32_t;
appears in <stdint.h>
in one C or C++ implementation does not mean it will appear in <stdint.h>
for any other C or C++ implementation. An implementation in which unsigned int
were not suitable for uint32_t
would have to provide a different <stdint.h>
. <stdint.h>
is part of the implementation and changes when the implementation changes.
Upvotes: 2
Reputation: 153457
uint32_t
guarantee 32 bits?
Yes.
If CHAR_BIT == 16
, uint32_t
would be 2 "bytes". A "byte" is not always 8 bits in C.
The size of int
is not a major issue concerning the implementation uintN_t
.
uintN_t
(N = 8,16,32,64) are optional non-padded types that independently exist when and if the system can support them. It is extremely common to find them implemented, especially the larger ones.
intN_t
is similarly optional and must be 2's complement.
Upvotes: 1
Reputation: 263257
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.
Upvotes: 10