Here are some guidelines for use of integer types in the Emacs C source code. These guidelines sometimes give competing advice; common sense is advised.
int len = strlen (s);unless the length of
sis required for other reasons to fit in
intfor Emacs character codes, in the range 0 .. 0x3FFFFF. More generally, prefer
intfor integers known to be in
intrange, e.g., screen column counts.
ptrdiff_tfor sizes, i.e., for integers bounded by the maximum size of any individual C object or by the maximum number of elements in any C array. This is part of Emacs’s general preference for signed types. Using
ptrdiff_tlimits objects to
PTRDIFF_MAXbytes, but larger objects would cause trouble anyway since they would break pointer subtraction, so this does not impose an arbitrary limit.
ssize_texcept when communicating to low-level APIs that have
ssize_t-related limitations. Although it’s equivalent to
ptrdiff_ton typical platforms,
ssize_tis occasionally narrower, so using it for size-related calculations could overflow. Also,
ptrdiff_tis more ubiquitous and better-standardized, has standard
printfformats, and is the basis for Emacs’s internal size-overflow checking. When using
ssize_t, please note that POSIX requires support only for values in the range −1 ..
intptr_tfor internal representations of pointers, or for integers bounded only by the number of objects that can exist at any given time or by the total number of bytes that can be allocated. However, prefer
uintptr_tto represent pointer arithmetic that could cross page boundaries. For example, on a machine with a 32-bit address space an array could cross the 0x7fffffff/0x80000000 boundary, which would cause an integer overflow when adding 1 to
EMACS_INTfor representing values converted to or from Emacs Lisp fixnums, as fixnum arithmetic is based on
time_t). Do not assume that a system type is signed, unless this assumption is known to be safe. For example, although
off_tis always signed,
time_tneed not be.
intmax_tfor representing values that might be any signed integer value. A
printf-family function can print such a value via a format like
truefor booleans. Using
boolcan make programs easier to read and a bit faster than using
int. Although it is also OK to use
1, this older style is gradually being phased out. When using
bool, respect the limitations of the replacement implementation of
bool. In particular, boolean bitfields should be of type
bool, so that they work correctly even when compiling Objective C with standard GCC.
intis less portable: it might be signed, and might not be. Single-bit bit fields should be
bool_bfso that their values are 0 or 1.