Using typedef in C Programming (Complete Guide with Examples)


This tutorial explains typedef in C, which allows creating new names (aliases) for existing data types. It covers syntax, examples, and practical use cases to make code shorter, readable, and easier to maintain.

1. What is typedef

  1. typedef is a keyword in C used to create an alias for an existing data type.
  2. It does not create a new type, just a new name for an existing type.
  3. Helps in simplifying complex declarations and improving code readability.

2. Syntax


typedef existing_data_type new_name;

3. Example: Basic typedef


#include <stdio.h>

typedef unsigned int uint;

int main() {
uint a = 100; // uint is an alias for unsigned int
printf("Value of a: %u\n", a);
return 0;
}

Sample Output:


Value of a: 100

4. Example: Typedef with Structures


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

typedef struct {
int id;
char name[50];
float marks;
} Student;

int main() {
Student s1;

s1.id = 101;
strcpy(s1.name, "Muni");
s1.marks = 95.5;

printf("ID: %d\n", s1.id);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n", s1.marks);

return 0;
}

Sample Output:


ID: 101
Name: Muni
Marks: 95.50

Observation: Using typedef avoids writing struct Student repeatedly and allows just Student.

5. Key Points to Remember

  1. typedef creates aliases, not new data types
  2. Makes code shorter, readable, and maintainable
  3. Can be used with basic types, arrays, pointers, and structures
  4. Commonly used in complex programs and libraries