Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing the most suitable integer size/range to use for variables

Tags:

c

integer

size

c99

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?

like image 335
x-x Avatar asked Oct 14 '10 06:10

x-x


1 Answers

I would say: Don't worry to much about this, it often is a form of premature optimisation. But my rules of thumb are:

  • Use plain int when possible. It should be the natural word size of the machine.
  • Use unsigned types when you need well-defined integer overflow.
  • Use an (u)intX_t type when you need two's-complement representation.
  • Use 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.

like image 170
schot Avatar answered Oct 17 '22 04:10

schot