Alex Rivera | Logout

What is the use of typedef?

Asked 2010-04-02T09:59:29.523
68

What is the use of typedef keyword in C ? When is it needed?

Edit
Report

2 Answers

18

Typedef is used to create aliases to existing types. It's a bit of a misnomer: typedef does not define new types as the new types are interchangeable with the underlying type. Typedefs are often used for clarity and portability in interface definitions when the underlying type is subject to change or is not of importance.

For example:

// Possibly useful in POSIX:
typedef int filedescriptor_t;

// Define a struct foo and then give it a typedef...
struct foo { int i; };
typedef struct foo foo_t;

// ...or just define everything in one go.
typedef struct bar { int i; } bar_t;

// Typedef is very, very useful with function pointers:
typedef int (*CompareFunction)(char const *, char const *);
CompareFunction c = strcmp;

Typedef can also be used to give names to unnamed types. In such cases, the typedef will be the only name for said type:

typedef struct { int i; } data_t;
typedef enum { YES, NO, FILE_NOT_FOUND } return_code_t;

Naming conventions differ. Usually it's recommended to use a trailing_underscore_and_t or CamelCase.

answered 2012-09-24T10:33:18.843
2

It can alias another type.

typedef unsigned int uint; /* uint is now an alias for "unsigned int" */
answered 2010-04-02T10:23:22.713

Your Answer