Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of typedef?

Tags:

c

typedef

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

like image 261
hks Avatar asked Apr 02 '10 09:04

hks


People also ask

What is the use of typedef in C with example?

typedef is a predefined keyword. You can replace the name of the existing data type with the name which you have provided. This keyword helps in creating a user-defined name for an existing data type. You can also use the typedef keyword with structures, pointers, arrays etc.

What is the need for typedef in C?

The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.

What is typedef example?

typedef struct { int scruples; int drams; int grains; } WEIGHT; The structure WEIGHT can then be used in the following declarations: WEIGHT chicken, cow, horse, whale; In the following example, the type of yds is "pointer to function with no parameter specified, returning int ".


2 Answers

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.

like image 86
T.J. Crowder Avatar answered Sep 20 '22 16:09

T.J. Crowder


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.

like image 33
Oded Avatar answered Sep 20 '22 16:09

Oded