typedef in C
typedef is a keyword used in C language to assign alternative names to existing datatypes. Its mostly used with user defined datatypes, when names of the datatypes become slightly complicated to use in programs. Following is the general syntax for using
typedef <existing_name> <alias_name>
Lets take an example and see how
typedef actually works.
typedef unsigned long ulong;
The above statement define a term
ulong for an
unsigned long datatype. Now this
ulong identifier can be used to define
unsigned long type variables.
ulong i, j;
Application of typedef
typedef can be used to give a name to user defined data type as well. Lets see its use with structures.
Here type_name represents the stucture definition associated with it. Now this type_name can be used to declare a variable of this stucture type.
type_name t1, t2;
Structure definition using typedef
Let's take a simple code example to understand how we can define a structure in C using
typedef struct employee
void main( )
printf("\nEnter Employee record:\n");
printf("\nEnter Employee salary: \t");
printf("\nstudent name is %s", e1.name);
printf("\nroll is %d", e1.salary);
typedef and Pointers
typedef can be used to give an alias name to pointers also. Here we have a case in which use of
typedef is beneficial during pointer declaration.
* binds to the right and not on the left.
int* x, y;
By this declaration statement, we are actually declaring
x as a pointer of type
y will be declared as a plain
typedef int* IntPtr;
IntPtr x, y, z;
But if we use
typedef like we have used in the example above, we can declare any number of pointers in a single statement.
NOTE: If you do not have any prior knowledge of pointers, do study Pointers first.