Tutorial - Understanding typedef in C
Tutorial
Compiled from multiple sources on the internet. Note that address values will change depending on the programming platform and operating system
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. The following is the general syntax for using typedef,
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.
typedef struct
{
type member1;
type member2;
type member3;
} type_name;
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 keyword.
#include<stdio.h>
#include<string.h>
typedef struct employee
{
char name[50];
int salary;
}emp;
int main( )
{
emp e1;
printf("\nEnter Employee record:\n");
printf("\nEmployee name:\t");
scanf("%s", e1.name);
printf("\nEnter Employee salary: \t");
scanf("%d", &e1.salary);
printf("\nstudent name is %s", e1.name);
printf("\nroll is %d", e1.salary);
return 0;
}
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.
Remember that in Pointers * 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 int, whereas y will be declared as a plain int variable.
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: In case of any doubts regarding pointers, please read the tutorial on pointers first.
Comments