typedef Example with structure in C

Here, we are going to learn how to declare a structure with typedef i.e. how to define an alias to the structure in C programming language?
By IncludeHelp Last updated : March 10, 2024

The structure is a user-defined data type, where we declare multiple types of variables inside a unit that can be accessed through the unit and that unit is known as "structure".

Simple structure declaration syntax

    struct structure_name{
        members_declarations;
    };   

As we know that – to access the structure members, we need an object of the structure – that is known as a structure variable.

Structure variable declaration of simple structure declaration Syntax:

    struct structure_name structure_variable;

Simple structure declaration Example:

    //normal structure declaration
    struct student_str 
    {
	    char name[30];
	    int age;
    };

Structure variable declaration of simple structure declaration Example:

    //declare structure variable for student_str
    struct student_str std;

Structure typedef

By using typedef keyword, we can define an alias of the structure.

Structure declaration with typedef Syntax:

    typedef struct{
        members_declarations;
    }structure_tag;

Structure variable declaration with typedef Syntax:

    structure_tag structure_name;

Note: There is no need to use struct keyword while declaring its variable.

Structure declaration with typedef Example

    //structur declaration with typedef
    typedef struct {
	    char name[30];
	    int age;
    }employee_str;

Structure declaration with typedef Example:

    //declare structure variable for employee_str
    employee_str emp;

Structure program/example with typedef in C

Here, we have two structures student_str and employee_str. student_str is declared by using normal (simple) way, while employee_str is declared by using typedef keyword.

C program for typedef Example with structure

#include <stdio.h>
#include <string.h>

//normal structure declaration
struct student_str 
{
	char name[30];
	int age;
};

//structur declaration with typedef
typedef struct {
	char name[30];
	int age;
}employee_str;

//main code
int main()
{
    
	//declare structure variable for student_str
	struct student_str std;
	//declare structure variable for employee_str
	employee_str emp;
	
	//assign values to std 
	strcpy(std.name, "Amit Shukla");
	std.age = 21;
	
	//assign values to emp
	strcpy(emp.name, "Abhishek Jain");
	emp.age = 27;
	
	//print std and emp structure 
	printf("Student detail:\n");
	printf("Name: %s\n",std.name);
	printf("Age: %d\n",std.age);
	
	printf("Employee detail:\n");
	printf("Name: %s\n",emp.name);
	printf("Age: %d\n",emp.age);	
	
	return 0;
}

Output

Student detail:
Name: Amit Shukla
Age: 21
Employee detail:
Name: Abhishek Jain
Age: 27

C typedef Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.