Simple Uses of Typedef

suggest change

For giving short names to a data type

Instead of:

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.

Improving portability

The widths of integer types vary across implementations. For example, int may be 16 bits in one implementation and 32 bits in another. Suppose a program needs a 32-bit type to run correctly.

In one implementation, let int be 16 bits and long be 32 bits. In another, let int be 32 bits and long be 64 bits. If the program is written for the second implementation,

/* program expecting a 32-bit integer */
int foo; /* needs to be 32 bits 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 long.

/* program now needs long */
long foo; /* needs to be 32 bits to work */
/* some code involving many more longs - lot to be changed */

To avoid this, one can use typedef

/* program expecting a 32-bit integer */
typedef int myint; /* declare once; this is the line to change */
myint foo; /* needs to be 32 bits 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> and <inttypes.h> define standard names for integers of particular widths. uint8_t is an unsigned 8-bit type and int64_t is a signed 64-bit type. uintptr_t is an unsigned integer type wide enough to hold any object pointer; it is not required to hold a function pointer. The exact-width types and uintptr_t are optional, though they are common. uint_least16_t (the smallest unsigned type with at least 16 bits), int_fast32_t (the fastest signed type with at least 32 bits), and the other least and fast types for 8, 16, 32, and 64 bits are required, as are intmax_t and uintmax_t.

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents