The typedef keyword lets you create a new name for an existing type. This makes your code easier to read and write.
0
0
Typedef keyword in C
Introduction
When you want to give a simple name to a complex type like a struct.
When you want to make your code easier to understand by using meaningful type names.
When you want to shorten long type names to save typing.
When you want to create platform-independent type names for better code portability.
Syntax
C
typedef existing_type new_type_name;
The existing_type can be any valid C type like int, struct, or pointer types.
The new_type_name becomes an alias you can use instead of the original type.
Examples
This creates a new name
uint for unsigned int. Now you can use uint instead of unsigned int.C
typedef unsigned int uint; uint age = 30;
This defines a struct with two integers and creates a new type name
Point for it. You can declare variables of type Point easily.C
typedef struct {
int x;
int y;
} Point;
Point p1 = {10, 20};This creates a new name
String for char*, making pointer usage clearer.C
typedef char* String; String name = "Alice";
Sample Program
This program uses typedef to create a new type Student for a struct. Then it creates a variable s1 of type Student and prints its fields.
C
#include <stdio.h>
typedef struct {
int id;
char name[20];
} Student;
int main() {
Student s1 = {101, "John"};
printf("ID: %d, Name: %s\n", s1.id, s1.name);
return 0;
}OutputSuccess
Important Notes
typedef does not create a new type, it creates a new name for an existing type.
You can use typedef with pointers, arrays, structs, and basic types.
Using typedef can make your code cleaner and easier to maintain.
Summary
typedef creates a new name for an existing type.
It helps simplify complex type names and improve code readability.
Commonly used with structs and pointers to make code easier to write and understand.