Define 16 bit integer in C

sara picture sara · Mar 21, 2012 · Viewed 80.4k times · Source

I need to declare an integer in the size of 16 bit, in C.

I know that short and int sizes are machine dependent.

I tried to use "stdint.h", but it seems that they simply do

typedef short int16_t

So my question is:

Am I missing something and short type guarantees 16 bit length?

If no, is there is an alternative that guarantees it?

Answer

maerics picture maerics · Mar 21, 2012

That means int16_t is defined as short on your machine, not all machines.

Just use the int16_t where you absolutely need a 16bit integer type; it will be defined as appropriate on all platforms that provide stdint.h (which should be all that support C99, or cstdint for C++).

[Edit] To clarify, the "stdint.h" header file is provided by the C (or C++) compiler, so its contents will likely vary per compiler, version, system, CPU architecture, etc. That is, the authors of the compiler suite know exactly what types have what sizes on which systems. Looking at that file on just one system only tells you about the definitions for a particular version of a particular compiler on a particular OS on a particular architecture (e.g. GCC 4.2 on Darwin x86_64, or Visual Studio on WinNT Alpha, or ICC on Solaris IA32, etc). Some systems, especially embedded ones, might have different type sizes, so a short might not always be 16 bits, and the compiler would know the right size to use for that bit length.

If you look at the file stdint.h on another system the definitions might be different, or they might be the same - but its purpose is to provide the definitions for integer types of guaranteed bit lengths.