Open In App

How to use typedef for a Struct in C?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C program to create a typedef for a structure
#include <stdio.h>
  
// Defining the structure
struct Student {
    char name[50];
    int age;
    float gpa;
};
  
// Creating a typedef for the struct
typedef struct Student St;
  
int main()
{
    // Declaring a variable using the typedef
    St student1;
  
    // Assigning values to the struct members
    snprintf(student1.name, sizeof(student1.name), "Ram");
    student1.age = 20;
    student1.gpa = 9.5;
  
    // Displaying the information of a student
    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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads