This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: C Integers


On 06/05/13 13:11, JimJoyce wrote:
> When Dennis Ritchie invented the C Programming language, he suggested that a
> short int would normally occupy 2 bytes, and a long int would take 4 bytes,
> and no matter what the hardware, a long should always be longer than a
> short. That makes sense.
> However, he was less precise about the simple int. He simply stated that it
> should reflect the 'natural' size of the hardware. So it might be like a
> short on one machine, while like a long on another.
> 
> Am I 'out of date' and 'out of touch'?
> Machines and compilers have grown in size since Ritchie's day
> When I check sizeof(short), sizeof(int) and sizeof(long) on my machine I get
> 2, 2, 4.

That is highly unlikely, unless you are using a cross-compiler.  It will
be 2, 4, 4 (for 32-bit Linux and 32-bit or 64-bit Windows) or 2, 4, 8
(64-bit Linux).

> Yet my machine is a 64bit one. Is that its 'natural' size. Should not my int
> be 8 bytes ??
> Should C and C++ compilers be re-defining shorts, ints and longs?
> 

The sizes of "short int", "int" and "long int" are not fixed in the C
standards, but there are certain rules.  "short int" must be at least 16
bits, "int" must be at least the size of "short int", "long int" must be
at least 32-bit and at least as bit as "int", and in newer standards,
"long long int" must be at least as bit as "long int".

In practice, "short int" is almost always 16 bit.  I can't think of any
target that does not have 16-bit shorts, except for a few odd DSP
architectures that have 32-bit as their minimum widths (all but the most
unlucky developers can ignore such systems).

"int" is 16-bit for 8-bit and 16-bit processors, and 32-bit for most
32-bit and 64-bit processors.  Again, there are a few oddities - there
are some old 64-bit systems like Crays that have 64-bit ints.

Note that it is the bit-width of the OS (or the target for the binary)
that is important, not the bit-width of the processor.

"long int" is typically 32-bit on 32-bit systems, and 64-bit on 64-bit
systems.  Microsoft, in traditional "we create our own standards"
fashion, made "long int" 32-bit on 64-bit Windows.

"long long int" are AFAIK invariably 64-bit - even on 8-bit compilers
(though few other than gcc for the AVR support them).

gcc also supports "__int128" on many platforms.


If you need specific sizes - and this is often a good idea - use
#include <stdint.h> and types such as int32_t, uint16_t, etc.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]