Two use cases for which I would consider short
come to mind:
ISO/IEC 9899:1999 (C99) adds headers <stdint.h> and <inttypes.h> that provide what you need:
int16_t
might not be defined, but if there is a 16-bit (exactly) integer type in the implementation, int16_t
will be an alias for it.int_least16_t
is a type that is the smallest type that holds at least 16 bits. It is always available.int_fast16_t
is the fastest type that holds at least 16 bits. It is always available.Similarly for other sizes: 8, 16, 32, 64.
There's also intmax_t
for the maximum precision integer type. Of course, there's also an unsigned type for each of these: uint16_t
etc.
These types are also present in C2011. They were not present in C89 or C90. However, I believe that the headers are available in some shape or form for most compilers, even those like MS Visual C, that do not claim to provide support for C99.
Note that I've given links to the POSIX 2008 versions of the <stdint.h>
and <inttypes.h>
headers. POSIX imposes rules on the implementation that the C standard does not:
§7.18.1.1 Exact-width integer types
¶1 The typedef name
int
N_t
designates a signed integer type with width N, no padding bits, and a two’s complement representation. Thus,int8_t
denotes a signed integer type with a width of exactly 8 bits.¶2 The typedef name
uint
N_t
designates an unsigned integer type with width N. Thus,uint24_t
denotes an unsigned integer type with a width of exactly 24 bits.¶3 These types are optional. However, if an implementation provides integer types with widths of 8, 16, 32, or 64 bits, it shall define the corresponding typedef names.
ANSI C specifies minimum value ranges for types. You can only be sure of the first case; not the second.
Yes, if you really want a particular data size you use int16_t, int32_t, etc.
int16_t is usually a platform-specific typedef from short (or whatever maps to 16 bits). On a 32-bit machine, int16_t may be typedef'd as short, on a 16-bit machine int16_t may be typedef as int.
If you have a very large array you might want to use shorts.
You might find them useful for picking out pieces of some other data as part of a union.
There is never a reason to use short
in a C99 environment that has 16-bit integers; you can use int16_t
, int_fast16_t
or int_least16_t
instead.
The main reasons for using short
is backward compatibility with C89 or older environments, which do not offer these types, or with libraries using short
as part of their public API, for implementing <stdint.h>
itself, or for compatibility with platforms that do not have 16-bit integers so their C compilers do not provide int16_t
.