typedef in C

typedef is a keyword in C that is used to create an **alias** (alternative name) for an existing data type.

It does **not** create a new type — it only gives a new meaningful name to an already existing type, making code more readable, maintainable, and portable.

• Improves code readability
• Makes complex declarations simple
• Very commonly used with structures, pointers, arrays, and function pointers
• Does NOT allocate memory — purely a compile-time feature

1. Basic Syntax

C
General syntax
typedef existing_type new_name;

2. Common and Useful Examples

Basic Types

C
typedef unsigned long long ull;

ull population = 1420000000ULL;

// Now ull is alias for unsigned long long

With Structures (Most Common Use)

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

// Now you can write:
Student s1, s2[30];

Pointer Types

C
typedef int* IntPtr;
IntPtr ptr1, ptr2;          // both are int*

// More readable for function pointers
typedef void (*FuncPtr)(int, float);
FuncPtr callback;

Arrays

C
typedef int Marks[5];
Marks student1 = {85, 92, 78, 88, 95};

Enums

C
typedef enum { RED, GREEN, BLUE } Color;
Color bg = GREEN;

3. typedef vs #define – Key Differences

Featuretypedef#define
TypeCreates type aliasText replacement (macro)
ScopeFollows C scoping rulesGlobal, preprocessor level
Can be used with pointers/arraysYes (correctly)No (needs extra care)
Error checkingCompiler checks typesNo type checking
Exampletypedef int* IntPtr;#define IntPtr int*
Common mistakeSafeIntPtr a, b; → int* a, b; (b is int!)

4. Best Practices & Naming Conventions

  • Use meaningful names: Student, Node, Point, CallbackFn, etc.
  • Common suffixes/prefixes:
  • - Ptr for pointers: IntPtr, NodePtr
  • - Fn for function pointers: CompareFn, SortFn
  • - No suffix for structures: Student, Book, Employee
  • Use typedef with anonymous structs (very common):
  • typedef struct { ... } Student;

5. Real-World & Standard Library Examples

  • size_t — typedef unsigned long/long long (platform dependent)
  • FILE — typedef struct _iobuf FILE;
  • wchar_t — typedef short/unsigned int/long (compiler dependent)
  • clock_t, time_t, ptrdiff_t — all typedefs
Note: typedef makes code portable across compilers and platforms