Programming with C

⌘K
  1. Home
  2. Docs
  3. Programming with C
  4. Structures
  5. typedef

typedef

typedef in C is used to create alternative names to the existing data types. It will be used when naming of the predefined data types becomes slightly complicated to use in the programs.

typedef is basically a reserved keyword that we use in order to create an alias name for a specific data type.

Syntax

typedef data_type new_your_data_type;

Example

typedef float my_float;
my_float b= 5.0;

Example Code

#include<stdio.h>
int main()
{
	typedef int myint;
	myint a = 5; // int a = 5; 
	printf("a=%d",a);
	return 0;
}

Output

a=5

Creating typedef for structures

Method 1

Syntax

typedef struct tagname
{
	statement(S);
} alias_name;

Example

typedef struct student
{
	int rollno;
	char name[10];
} stud;
stud s1, st[20];

Method 2

Syntax

struct tagname
{
	statement(S);
};
typedef struct tagname alias_name var_list;

Example Code

struct phonebook
{
	NAME pname; // pname is a variable of type name
	char mob_no[11];
};
typedef struct phonebook phentry;

Example: Using typedef for structures

#include<stdio.h>
typedef struct name
{
	char first_name[20];
	char last_name[20];
}NAME; // NAME is a new datatype for struct name
struct phonebook
{
	NAME pname; // pname is a variable of type name
	char mob_no[11];
};
typedef struct phonebook phentry; // phentry is a new datatype for struct phonebook
int main()
{
	phentry p1,p2; // p1 and p2 are variables for phentry
	printf("Enter the details of the first person:\n");
	printf("Enter the first name of the person \t");
	gets(p1.pname.first_name);
	printf("Enter the last name of the person \t");
	gets(p1.pname.last_name);
	printf("Enter the mobile number of the person \t");
	gets(p1.mob_no);
	
	printf("Enter the details of the second person:\n");
	printf("Enter the first name of the person \t");
	gets(p2.pname.first_name);
	printf("Enter the last name of the person \t");
	gets(p2.pname.last_name);
	printf("Enter the mobile number of the person \t");
	gets(p2.mob_no);
	
	printf("****Details are****\n");
	printf("---------------------\n");
	printf("%s\t %s\t %10s\n",p1.pname.first_name,p1.pname.last_name,p1.mob_no);
	printf("%s\t%s\t%10s\n",p2.pname.first_name,p2.pname.last_name,p2.mob_no);
}

Output

C:\TDM-GCC-64>gcc 4_typedef1.c -o 4t1
C:\TDM-GCC-64>4t1
Enter the details of the first person:
Enter the first name of the person      abi
Enter the last name of the person       kumar
Enter the mobile number of the person   123456
Enter the details of the second person:
Enter the first name of the person      ram
Enter the last name of the person       laxman
Enter the mobile number of the person   23456
****Details are****
---------------------
abi      kumar       123456
ram     laxman       23456

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments