Use of typedef in structure

typedef keyword can also be used to change the name of the user-defined datatype.

Let’s see the use of typedef to change the structure’s name.

Syntax

typedef struct structure_name
{
data-type member-1;
data-type member-1;
data-type member-1;
} type_name;

 

Example

typedef struct Month
{
int days;
char name;
}sm;

 

In the above example, we assign a new name ‘sm’ to the structure ‘Month’. Thus, in the ‘main’ function we will use the ‘sm’ data type to declare variables of structure.

Let’s see the same example we discussed in the structure chapter. But this time with the use of typedef keyword.

Program

#include<stdio.h>
#include<string.h>
typedef struct student
{
char name[20];
int age;
float weight;
float height;
}st;
int main()
{
printf("Details of the student are as below:\n");


st s1={"Brown",20,65.5,172.72 };
printf("\nFirst Student\n");
printf("Name:%s\n",s1.name);
printf("Age:%d\n",s1.age);
printf("Height:%.2f\n",s1.height);
printf("Weight:%.2f\n",s1.weight);


st s2;
strcpy(s2.name,"Thomson");
s2.age=21;
s2.weight=70;
s2.height=175.0;
printf("\nSecond Student\n");
printf("Name:%s\n",s2.name);
printf("Age:%d\n",s2.age);
printf("Height:%.2f\n",s2.height);
printf("Weight:%.2f\n",s2.weight);
return 0;
}

 

Output

The above code is identical to the code we did in the ‘structure’ chapter.

The only difference is that we use ‘st’ instead of ‘struct student’, which is used as a data type to declare the variables s1, and s2 for the structure.

It is clearly, visible that in place of writing such a large data type ‘struct student’, we just write ‘st’.

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.