Just using int
everywhere may seem tempting, since it minimizes the need for casting, but there are several potential pitfalls you should be aware of:
-
An
int
might be shorter than you expect. Even though, on most desktop platforms, anint
is typically 32 bits, the C standard only guarantees a minimum length of 16 bits. Could your code ever need numbers larger than 216−1 = 32,767, even for temporary values? If so, don’t use anint
. (You may want to use along
instead; along
is guaranteed to be at least 32 bits.) -
Even a
long
might not always be long enough. In particular, there is no guarantee that the length of an array (or of a string, which is achar
array) fits in along
. Usesize_t
(orptrdiff_t
, if you need a signed difference) for those.In particular, a
size_t
is defined to be large enough to hold any valid array index, whereas anint
or even along
might not be. Thus, for example, when iterating over an array, your loop counter (and its initial / final values) should generally be asize_t
, at least unless you know for sure that the array is short enough for a smaller type to work. (But be careful when iterating backwards:size_t
is unsigned, sofor(size_t i = n-1; i >= 0; i--)
is an infinite loop! Usingi != SIZE_MAX
ori != (size_t) -1
should work, though; or use ado
/while
loop, but beware of the casen == 0
!) -
An
int
is signed. In particular, this means thatint
overflow is undefined behavior. If there’s ever any risk that your values might legitimately overflow, don’t use anint
; use anunsigned int
(or anunsigned long
, oruintNN_t
) instead. -
Sometimes, you just need a fixed bit length. If you’re interfacing with an ABI, or reading / writing a file format, that requires integers of a specific length, then that’s the length you need to use. (Of course, is such situations, you may also need to worry about things like endianness, and so may sometimes have to resort to manually packing data byte-by-byte anyway.)
All that said, there are also reasons to avoid using the fixed-length types all the time: not only is int32_t
awkward to type all the time, but forcing the compiler to always use 32-bit integers is not always optimal, particularly on platforms where the native int
size might be, say, 64 bits. You could use, say, C99 int_fast32_t
, but that’s even more awkward to type.
Thus, here are my personal suggestions for maximum safety and portability:
-
Define your own integer types for casual use in a common header file, something like this:
#include <limits.h> typedef int i16; typedef unsigned int u16; #if UINT_MAX >= 4294967295U typedef int i32; typedef unsigned int u32; #else typedef long i32; typedef unsigned long i32; #endif
Use these types for anything where the exact size of the type doesn’t matter, as long as they’re big enough. The type names I’ve suggested are both short and self-documenting, so they should be easy to use in casts where needed, and minimize the risk of errors due to using a too-narrow type.
Conveniently, the
u32
andu16
types defined as above are guaranteed to be at least as wide asunsigned int
, and thus can be used safely without having to worry about them being promoted toint
and causing undefined overflow behavior. -
Use
size_t
for all array sizes and indexing, but be careful when casting between it and any other integer types. Optionally, if you don’t like to type so many underscores,typedef
a more convenient alias for it too. -
For calculations that assume overflow at a specific number of bits, either use
uintNN_t
, or just useu16
/u32
as defined above and explicit bitmasking with&
. If you choose to useuintNN_t
, make sure to protect yourself against unexpected promotion toint
; one way to do that is with a macro like:#define u(x) (0U + (x))
which should let you safely write e.g.:
uint32_t a = foo(), b = bar(); uint32_t c = u(a) * u(b); /* this is always unsigned multiply */
-
For external ABIs that require a specific integer length, again define a specific type, e.g.:
typedef int32_t fooint32; /* foo ABI needs 32-bit ints */
Again, this type name is self-documenting, with regard to both its size and its purpose.
If the ABI might actually require, say, 16- or 64-bit ints instead, depending on the platform and/or compile-time options, you can change the type definition to match (and rename the type to just
fooint
) — but then you really do need to be careful whenever you cast anything to or from that type, because it might overflow unexpectedly. -
If your code has its own structures or file formats that require specific bitlengths, consider defining custom types for those too, exactly as if it was an external ABI. Or you could just use
uintNN_t
instead, but you’ll lose a little bit of self-documentation that way. -
For all these types, don’t forget to also define the corresponding
_MIN
and_MAX
constants for easy bounds checking. This might sound like a lot of work, but it’s really just a couple of lines in a single header file.
Finally, remember to be careful with integer math, especially overflows.
For example, keep in mind that the difference of two n-bit signed integers may not fit in an n-bit int. (It will fit into an n-bit unsigned int, if you know it’s non-negative; but remember that you need to cast the inputs to an unsigned type before taking their difference to avoid undefined behavior!)
Similarly, to find the average of two integers (e.g. for a binary search), don’t use avg = (lo + hi) / 2
, but rather e.g. avg = lo + (hi + 0U - lo) / 2
; the former will break if the sum overflows.