C – Typedef

Introduction:

  • typedef is a user-defined data type specifier.
  • Using typedef we can define identifiers (synonyms) for data types.
  • We can use synonyms instead of original data types.

Advantage: Synonyms to data types become more readable than complex identities

Giving the name Integer to int type:

#include<stdio.h>
int main()
{
            typedef int Integer ;
            Integer a=10,b=20,c;
            c = a+b;
            printf(“res : %d\n”,c);
            return 0;
}

Creating Synonym to Array:

#include<stdio.h>
int main()
{
            typedef int Arry[5];
            int i;
            Array arr = {10,20,30,40,50};
            printf(“Array elements are\n”);
            for(i=0 ; i<5 ; i++)
            {
                        printf(“%d\n”, arr[i]);
            }
            return 0;
}

The main advantage of typedef declaration is giving simple identity for complex types.

For example, char* can simply represent with name String.

#include<stdio.h>
typedef char* String;
String read(void);
int main()
{
            String name;
            name = read();
            printf(“welcome %s\n”,name);
}
String read()
{
            String name;
            printf(“Enter one name : “);
            gets(name);
            return name;
}

Typedef declaration to Structures:

  • Generally, identity of Structure is a combination of two words.
  • For example, struct Emp
  • We can give one word to structure type then representation become easy.
#include<stdio.h>
typedef struct Emp
{
            int eno;
            char* ename;
            float esal;
} Employee;
int main()
{
            Employee e;
}
#include<stdio.h>
struct Emp
{
            int eno;
            char* ename;
            float esal;
};
int main()
{
            typedef struct Emp Employee;
            Employee e;
}

By using typedef declarations, we can shorten the size of instructions:

#include<stdio.h>
struct Emp
{
            int eno;
            char* ename;
            float esal;
};
int main()
{
            typedef struct Emp Employee;
            typedef struct Emp* Ptr;
            Ptr e;
            e = (Ptr)malloc(sizeof(Employee));
}
Scroll to Top