CoffeeGood wrote:
Most of the time I don't care what size my variables really are.
I just need them to be some minimum size.
That's reasonable to me, but in this newsgroup saying
such a thing could be considered unforgivable heresy.
Err.... why? The topic of this ng is standard C. Writing standard C in
fact *requires* that you only rely on guaranteed minimum sizes.
"Heresy" would be assuming that a short is 16 bits, an int 32 bits, that
you can safely convert pointers of all types to ints and back, that a
null pointer is represented by all-bits-zero... that sort of thing.
I think you're confusing a minimum size with an exact size. That is, if
you do something like this:
typedef char int8_t;
typedef short int16_t;
typedef int int32_t;
With the intention that intN_t is a signed integer type of exactly N
bits. This renders code unportable on all platforms that don't meet the
assumptions this implies: that a char is 8 bits (and plain char is
signed), that a short is 16 bits, an int 32 bits.
If you isolate these typedefs and make it clear they are to be
customized for every platform, you're still relying on the assumption
that the types you want exist at all. Some platforms will simply not
*have* signed integer types of exactly 8, 16 or 32 bits.
If, as is usual, you actually don't need *exact* sizes (since this is
mostly interesting for interfacing with low-level bits that don't need
much in the way of portability anyway) but are content with minimally
adequate types, portability is easier. C89 already gives you standard
integer types of at least 8, 16 and 32 bits: char, int and long.
C99 makes this even easier with <stdint.h>, which includes the intN_t
typedefs above (where the corresponding types exist), as well as uintN_t
for the unsigned counterparts, and (u)int_leastN_t for integers of at
least a certain size. C99 furthermore requires that (u)int_leastN_t
types exist for N = 8, 16, 32 or 64, and defines macros for the minimum
and maximum values of all of these types.
This makes writing portable code that much easier. You can do, for example:
#include <stdint.h>
typedef uint16_t word;
For poorly written or platform-specific code that requires exact 16-bit
quantities. This code will fail to compile on platforms that don't have
such a type, but will not require any modification for those platforms
that do. You can even do:
#include <stdint.h>
#ifndef INT_LEAST24_MIN
typedef int_least32_t int_least24_t;
#define INT_LEAST24_MIN INT_LEAST32_MIN
#define INT_LEAST24_MAX INT_LEAST32_MAX
#define INT24_C(x) INT32_C(x)
#endif
This gives you a platform-specific integer type of at least 24 bits
long, using the platform's 32-bit integer type if necessary.
S.