How to use typedef for a Struct in C?
Last Updated :
19 Feb, 2024
In C, we use typedef to create aliases for already existing types. For structure, we can define a new name that can be used in place of the original struct name. In this article, we will learn how to create a typedef for a structure in C++.
Use the typedef struct in C
To create an alias for a structure in C, we can use the typedef keyword typedef for a structure that provides the existing datatype with a new name.
Syntax
For defining the structure and creating a typedef simultaneously use:
typedef struct StructName {
// Member definitions
} TypedefName;
For defining the Structure first, then creating a typedef use:
struct StructName {
// Member definitions
};
typedef struct StructName TypedefName;
C Program to Create an Alias Using typedef for a struct
The below program demonstrates the use typedef keyword to create a typedef for a structure in C.
C
#include <stdio.h>
struct Student {
char name[50];
int age;
float gpa;
};
typedef struct Student St;
int main()
{
St student1;
snprintf(student1.name, sizeof (student1.name), "Ram" );
student1.age = 20;
student1.gpa = 9.5;
printf ( "Student Information:\n" );
printf ( "Name: %s\n" , student1.name);
printf ( "Age: %d\n" , student1.age);
printf ( "GPA: %.2f\n" , student1.gpa);
return 0;
}
|
Output
Student Information:
Name: Ram
Age: 20
GPA: 9.50
Share your thoughts in the comments
Please Login to comment...