stdint.h in C99 provides many options for integer sizes, types and ranges - so many I don't know what ones to choose!
I know how to use size_t
and ptrdiff_t
when appropriate, and I use fixed size types for storage and transmission. My question concerns values that will only be stored in memory of the host machine.
For example, a structure for an image might contain these members:
struct image {
integer width, height; /* pixel dimensions of the image */
integer bits_per_pixel;
...
};
If width
and height
will never exceed SHRT_MAX
, should a short
be used, or stick with int
? An image can't have negative width or height, so use an unsigned type? Perhaps (u)int_least16_t
is the correct choice? Something else?
If bits_per_pixel
will never exceed a value of 64 use char
, unsigned char
, uint8_t
, int
or something else?
What would you use in this example and why?
How does the CPU architecture the code will run on affect the choice? i.e. PPC or x86, 32 or 64bit.
How does the device the code will run on affect the choice? i.e. Desktop, phone, console.
How does the choice relate to performance and optimization?
My question in simple terms is: How do you choose which integer to use?
I would say: Don't worry to much about this, it often is a form of premature optimisation. But my rules of thumb are:
int
when possible. It should be the natural word size of the machine.unsigned
types when you need well-defined integer overflow.(u)intX_t
type when you need two's-complement representation.unsigned char
for large arrays with values <= UCHAR_MAX
.Beware that a lot of the types in <stdint.h>
are optional, so you can't depend on their existence. POSIX makes this slightly better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With