C Data Types – Purpose of Short, Int, and Long

cdata types

I'm having trouble understanding, what were the exact purposes of creating the short, int, and long data types in C?

The reason I ask is, it doesn't seem like their sizes are bounded — they could be of any size, so long as short is smaller than an int, for example.

In which situations, then, should you use an unsigned int or unsigned long, for example, instead of a size_t, when doing so offers no hope of binary compatibility?

(If you don't know the size, then how would you know when to choose which?)

Best Answer

It'd be defined by the architecture you were using. On a Zilog z80 chip (common embedded chip) they'd be one size while they could be an entirely different size on a x86 chipset. However, the sizes themselves are fixed ratios to each other. Essentially short and long aren't types but qualifies for the int type. Short ints will be one order of magnitude smaller than (regular) int and long ints will be an order of magnitude higher. So say your Int is bounded to 4 bytes, the short qualifier bounds it to 4 bytes though 2 bytes is also very common and the long qualifier boosts it potentially to 8 bytes though it can be less down to 4 bytes. Keep in mind that this is subject to word length as well so on a 32 bit system you'd max out at 4 bytes per int anyway making long the same as a regular int. Thus, Short ≤ Int ≤ Long.

However, if you lengthen it again, you can push in the int to the next cell giving you 8 whole bytes of storage. This is the word size for 64 bit machines so they don't have to worry about such things and just use the one cell for long ints allowing them to be another order above standard ints while long long ints get really bit.

As far as which to choose, it boils down to something that Java programmers for instance don't have to worry about. "What is your architecture?" Since it all depends on the word size of the memory of the machine in question, you have to understand that up front before you decide which to use. You then pick the smallest reasonable size to save as much memory as you can because that memory will be allocated whether you use all of the bits in it or not. So you save where you can and pick shorts when you can and ints when you can't and if you need something bigger than what regular ints you give; you'd lengthen as needed until you hit the word ceiling. Then you'd need to supply big number routines or get them from a library.

C may well be "portable assembly" but you still have to know thine hardware.