So I am programming in C++, and as far as I can tell there is no C++ equivalent to stdint.h. Which is no problem, seeing as you can just grab a copy of stdint and include it... but my question is basically this,
what is the difference between these two pieces of code:
struct FREQ{
unsigned int FREQLOHI :16;
//etc...
};
and
struct FREQ{
uint16_t FREQLOHI;
//etc...
}
other than the obvious limitations of bitfields, is there a performance/portability issue? Which is preferred?
The difference is that
unsigned int
may be of different size on different platforms while uint16_t is guaranteed to have 16 bit width. This means that an instance of the first (bitfield) struct may have different size on different platforms. Also, bitfield access is more expensive since it involves extra shift and mask.For example on laptop where unsigned int is 32-bit wide the first struct is 32-bit wide while the second struct is 16-bit.
When it comes to portability, bit-fields are in a much cleaner situation since it is an old C language feature that was included in C++ when it was standardized in 1998 (ISO/IEC 14882:1998). On the other hand
stdint.h
was added to C only in 1999 (ISO/IEC 9899:1999 standard) and hence is not part of C++98 (ISO/IEC 14882:1998). The corresponding headercstdint
was then incorporated into C++ TR1, but it put all the identifiers instd::tr1
namespace. Boost also offered the header. The most recent C++ standard (C++11 aka ISO/IEC 14882:2011 that went out in September 2011) includes the headercstdint
and it puts all the identifiers into thestd
namespace. Despite this,cstdint
is widely supported.