typedef Keyword in C

typedef in C is used to create a new name (alias) for an existing data type. It improves readability, shortens complex declarations, and makes code cleaner.

What is typedef?

The typedef keyword allows you to assign a custom name to any datatype (built-in, struct, pointer, array, etc.).

Basic Syntax

typedef existing_type new_name;
Example:
typedef int Marks;
Marks m1 = 80;

Why Use typedef?

Examples of typedef

1. typedef for int

#include <stdio.h>

typedef int Number;

int main() {
    Number a = 10;
    printf("%d", a);
    return 0;
}

2. typedef for float

#include <stdio.h>

typedef float Price;

int main() {
    Price p = 99.75;
    printf("%.2f", p);
    return 0;
}

3. typedef for a pointer

#include <stdio.h>

typedef int* IntPtr;

int main() {
    int a = 10;
    IntPtr p = &a;
    printf("%d", *p);
    return 0;
}

4. typedef for array

#include <stdio.h>

typedef int Marks[5];

int main() {
    Marks m = {10,20,30,40,50};
    printf("%d", m[2]);
    return 0;
}

5. typedef with struct

#include <stdio.h>

typedef struct {
    int roll;
    char name[20];
} Student;

int main() {
    Student s = {1, "Sourav"};
    printf("%d %s", s.roll, s.name);
    return 0;
}

6. typedef struct + pointer

#include <stdio.h>

typedef struct {
    int x, y;
} Point;

int main() {
    Point p = {10, 20};
    printf("%d %d", p.x, p.y);
    return 0;
}

7. typedef with unsigned types

#include <stdio.h>

typedef unsigned long ULong;

int main() {
    ULong num = 999999;
    printf("%lu", num);
    return 0;
}

8. typedef for function pointer

#include <stdio.h>

typedef int (*FunPtr)(int,int);

int add(int a, int b) { return a + b; }

int main() {
    FunPtr f = add;
    printf("%d", f(5, 6));
    return 0;
}

Where typedef Is Used in Real Life?

Practice Questions

  1. What is typedef? Why is it used?
  2. Write syntax of typedef for array.
  3. Create typedef for structure Employee.
  4. Create typedef for pointer to integer.
  5. Difference between #define and typedef?

Practice Task

Create a typedef for a Book structure with fields: ✔ title ✔ author ✔ price Then create an array of 3 books and print their details.