What is the use of typedef?

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


Solution 1:

typedef is for defining something as a type. For instance:

typedef struct {
  int a;
  int b;
} THINGY;

...defines THINGY as the given struct. That way, you can use it like this:

THINGY t;

...rather than:

struct _THINGY_STRUCT {
  int a;
  int b;
};

struct _THINGY_STRUCT t;

...which is a bit more verbose. typedefs can make some things dramatically clearer, specially pointers to functions.

Solution 2:

From wikipedia:

typedef is a keyword in the C and C++ programming languages. The purpose of typedef is to assign alternative names to existing types, most often those whose standard declaration is cumbersome, potentially confusing, or likely to vary from one implementation to another.

And:

K&R states that there are two reasons for using a typedef. First, it provides a means to make a program more portable. Instead of having to change a type everywhere it appears throughout the program's source files, only a single typedef statement needs to be changed. Second, a typedef can make a complex declaration easier to understand.

And an argument against:

He (Greg K.H.) argues that this practice not only unnecessarily obfuscates code, it can also cause programmers to accidentally misuse large structures thinking them to be simple types.