Integer Variable Length in C/C++ on Different Platforms

While writing codes for multiple platform (in terms of both OS and CPU Arch), making the code independent of the exact byte size of each integer type in c/c++ on each specific platform becomes a typical challenging problem.

What about the ANSI C standard regarding this problem?

The standard defines 5 standard integer types:
- unsigned char - short int - int - long int - long long int

It also defines some limitations on these types in limits.h

But it didn't say explicitly on the exact byte size of each type.

Common understanding on the standard is that it requires:
sizeof(short int) <= sizeof(int) <= sizeof(long int)  sizeof(long long int)
So how about popular compiler's documentation on this?

Visual Studio 10 has an article on MSDN describes the exact size of each integer type.

From that article we can see:
sizeof(short int) = 2
sizeof(int) = 4
sizeof(long int) = 4
sizeof(long long int) = 8

And these constrains are true on both 32/64 bit platforms.

To help programmer aware of the exact size of integer types they are using, vs 10 introduces some other integer types:
__int8, __int16, __int32, __int64 and their unsigned counter parts.

In fact, ANSI c99 also defined those fixed width integer types in stdint.h

To scanf() and printf()? The format string for these types are defined in the standard header - inttypes.h. For example, this is inttypes.h for visual studio.

And here is a good summary on how to use format strings to deal with integer types in c/c++

1. stdint.h in C99
2. Integer Types in VS10
3. ANSI C99 Spec
4. Integers in C99

No comments: