Accepted type name (i.e. typedef) in C and C++ for a 4-byte signed integer type. Alas, C need not run on a platform on which such a type is natively available, so the standard doesn't specify its existence (you are, however, guaranteed that int is a "fast" signed integer type which can hold at least all the values that a 2's complement 4-byte signed integer could hold).

But any "reasonable" (for varying definitions of "reasonable") platform will have one of these; the problem is how to define such a type in a portable manner. The problem, of course, is that it's not possible to use sizeof in C preprocessor conditionals (it's expanded too late).

Here's a solution that works for C (a more C++-ish way uses typelists; you can find it as Int<bits>). It's standard, but may fail to define a type if none of short, int and long are the right size. You might care to add signed char, for some really weird platforms (Cray?).

#include <limits.h>

/* int32 = 32-bit (signed) int */
#if	(INT_MAX == 2147483647L)
typedef int int32;
#define I32FMT  "d"
#elif	(LONG_MAX == 2147483647L)
typedef long int32;
#define I32FMT  "ld"
#elif (SHORT_MAX == 2147483647L)
typedef short int32;
#define I32FMT  "hd"
#elif	defined(CRASH_BURN)
typedef void int32;
#define	I32FMT	"*d"
#endif

Notes:

  1. If no suitable type is found, none is defined; this will cause errors when int32 is used. You may alternatively wish to #define CRASH_BURN, which will cause a different type of error to occur.
  2. The code also #defines a macro I32FMT which is appropriate to use with printf() and scanf(). For instance:
    int32 x;
    scanf(I32FMT, &x);
    printf("x = %" I32FMT "\n", x);
    
    Note the use of string pasting to create an appropriate string literal at compile time.

Log in or register to write something here or to contact authors.