Simple Uses of Typedefsuggest change
For giving short names to a data type
long long int foo; struct mystructure object;
one can use
/* write once */ typedef long long ll; typedef struct mystructure mystruct; /* use whenever needed */ ll foo; mystruct object;
This reduces the amount of typing needed if the type is used many times in the program.
The attributes of data types vary across different architectures. For example, an
int may be a 2-byte type in one implementation and an 4-byte type in another. Suppose a program needs to use a 4-byte type to run correctly.
In one implementation, let the size of
int be 2 bytes and that of
long be 4 bytes. In another, let the size of
int be 4 bytes and that of
long be 8 bytes. If the program is written using the second implementation,
/* program expecting a 4 byte integer */ int foo; /* need to hold 4 bytes to work */ /* some code involving many more ints */
For the program to run in the first implementation, all the
int declarations will have to be changed to
/* program now needs long */ long foo; /*need to hold 4 bytes to work */ /* some code involving many more longs - lot to be changed */
To avoid this, one can use
/* program expecting a 4 byte integer */ typedef int myint; /* need to declare once - only one line to modify if needed */ myint foo; /* need to hold 4 bytes to work */ /* some code involving many more myints */
Then, only the
typedef statement would need to be changed each time, instead of examining the whole program.
<stdint.h> header and the related
<inttypes.h> header define standard type names (using
typedef) for integers of various sizes, and these names are often the best choice in modern code that needs fixed size integers. For example,
uint8_t is an unsigned 8-bit integer type;
int64_t is a signed 64-bit integer type. The type
uintptr_t is an unsigned integer type big enough to hold any pointer to object. These types are theoretically optional — but it is rare for them not to be available. There are variants like
uint_least16_t (the smallest unsigned integer type with at least 16 bits) and
int_fast32_t (the fastest signed integer type with at least 32 bits). Also,
uintmax_t are the largest integer types supported by the implementation. These types are mandatory.
To specify a usage or to improve readability
If a set of data has a particular purpose, one can use
typedef to give it a meaningful name. Moreover, if the property of the data changes such that the base type must change, only the
typedef statement would have to be changed, instead of examining the whole program.