Categories: C

Typedef in C

Typedef in C is used to redefine the name of the existing variable type. It generally increases the readability and convenience of complex data types.

Syntax:
typedef <name_of_data> <alias_name>;

For instance, consider the following statement in which the type unsigned long int is redefined to be of the type TWOWORDS:

unsigned long int var1, var2;
typedef unsigned long int TWOWORDS;
TWOWORDS var1,var2;

Thus, typedef in C provides a short and meaningful way to call a data type. Usually, uppercase letters are used to make it clear that we are dealing with a renamed data type

We can also use typedef with structures:

struct employee 
{
    char name[30];
    int age;
    float bs;
};

typedef struct employee EMP;
EMP e1, e2;
Example:
#include<stdio.h>
struct employee 
{
    char name[30];
    int age;
    float bs;
};

typedef struct employee P;
P e1, e2;
void main( )
{
   
    printf("\nEnter Employee record:\n");
    printf("\nEmployee name:\t");
    scanf("%s", e1.name);
    printf("\nEnter Employee salary: \t");
    scanf("%d", &e1.age);
    printf("\n name is %s", e1.name);
    printf("\nsalary is %d", e1.age);
}
Output:
Enter Employee record:

Employee name: Coderzpy
Enter Employee salary:  190000
name is Coderzpy
salary is 190000

Thus, by reducing the length and clear complexness of data types, typedef can help to clarify source listing and save time and energy spent in understanding a program.

typedef can also be used to rename pointer data types as shown:

struct employee 
{
    char name[30];
    int age;
    float bs;
};

typedef struct employee * P;
P e1, e2;
e1->age =32;

Note: also read about the Nested Structure in C

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago