Two use cases for which I would consider short
come to mind:
- I want an integer type that's at least 16 bits in size
- I want an integer type that's exactly 16 bits in size
In the first case, since int
is guaranteed to be at least 16 bits and is the most efficient integral data type, I would use int
. In the second case, since the standard doesn't guarantee that short
's size is exactly 16 bit, I would use int16_t
instead. So what use is short?
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.
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.
There is never a reason to use
short
in a C99 environment that has 16-bit integers; you can useint16_t
,int_fast16_t
orint_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 usingshort
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 provideint16_t
.ANSI C specifies minimum value ranges for types. You can only be sure of the first case; not the second.
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: