Skip to content
StudyFame

typedef in C

Writing struct student every single time gets tiring. And declarations like int (*op)(int, int) are hard to read. typedef lets you give any type a short, meaningful name.

In this lesson you will create type aliases with typedef, use it with structures, pointers and function pointers, and learn how it differs from #define, a common viva question.

What You Will Learn

  • What typedef does (and doesn't do).
  • How to create simple type aliases.
  • How to use typedef with structures.
  • How to use typedef with pointers and function pointers.
  • The difference between typedef and #define.

What is typedef in C?

Exam definition: typedef is a keyword used to create an alias (a new name) for an existing data type. It does not create a new type; it only gives an existing type another name, making code shorter and easier to read.

Memory trick: typedef is a nickname. Your friend "Rajesh Kumar Sharma" is called "Raju": same person, shorter name. typedef unsigned long long ull; → ull is Raju for unsigned long long.

Syntax of typedef

typedef existing_type new_name;

typedef unsigned int uint;          /* uint  = unsigned int */
typedef float marks_t;              /* marks_t = float      */

uint count = 10;                    /* same as: unsigned int count = 10; */

Easy rule: write a normal variable declaration, then put typedef in front. The "variable name" becomes the new type name.

int  *IntPtr;           ->  typedef int *IntPtr;           IntPtr is "int *"
int  Row[3];            ->  typedef int Row[3];            Row is "array of 3 ints"
int  (*Op)(int, int);   ->  typedef int (*Op)(int, int);   Op is a function pointer type

typedef with structures: three styles

/* Style 1: define, then typedef */
struct student { int roll; float cgpa; };
typedef struct student Student;

/* Style 2: typedef in the same statement (most common) */
typedef struct student { int roll; float cgpa; } Student;

/* Style 3: anonymous struct (no tag) */
typedef struct { int roll; float cgpa; } Student;

Student s1;          /* no need to write "struct" */

For a self-referential structure (like a linked list node), keep the tag, because the alias doesn't exist yet inside the braces:

typedef struct node
{
    int data;
    struct node *next;       /* must use "struct node" here */
} Node;

Example 1: typedef with Basic Types and Structures

#include <stdio.h>

typedef unsigned long long ull;
typedef float marks_t;

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

ull factorial(int n)
{
    ull f = 1;
    int i;
    for (i = 2; i <= n; i++)
        f *= i;
    return f;
}

int main(void)
{
    Student s = {101, "Asha", 87.5f};      /* no "struct" keyword needed */
    Student *p = &s;

    printf("%d %s %.1f\n", s.roll, s.name, s.marks);
    p->marks += 2.5f;
    printf("After update: %.1f\n", p->marks);

    printf("20! = %llu\n", factorial(20));
    printf("sizeof(ull) = %zu\n", sizeof(ull));

    return 0;
}

Output

101 Asha 87.5
After update: 90.0
20! = 2432902008176640000
sizeof(ull) = 8

Code Explanation

  1. typedef unsigned long long ull;: ull is now a short name for a long type. Its format specifier is still %llu; typedef changes only the name.
  2. typedef float marks_t; documents meaning: anyone reading marks_t knows it holds marks. If you later need double, change one line.
  3. typedef struct { ... } Student; lets us write Student s and Student *p.
  4. sizeof(ull) is 8: the alias is the same type as unsigned long long.

How typedef Helps with Pointers and Function Pointers

typedef shines with complicated declarations. Compare:

/* without typedef */
int (*menu[4])(int, int);
void apply(int arr[], int n, int (*action)(int));

/* with typedef */
typedef int (*BinaryOp)(int, int);
typedef int (*UnaryOp)(int);

BinaryOp menu[4];
void apply(int arr[], int n, UnaryOp action);

Much easier to read. The standard library does the same: size_t, FILE, time_t and ptrdiff_t are all typedef names.

Example 2: typedef for Function Pointers and a Linked Node

#include <stdio.h>

typedef int (*BinaryOp)(int, int);

typedef struct node
{
    int data;
    struct node *next;
} Node;

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }

int main(void)
{
    BinaryOp ops[3] = {add, sub, mul};
    const char *sym = "+-*";
    Node n3 = {3, NULL}, n2 = {2, &n3}, n1 = {1, &n2};
    Node *walk;
    int i;

    for (i = 0; i < 3; i++)
        printf("9 %c 4 = %d\n", sym[i], ops[i](9, 4));

    printf("List: ");
    for (walk = &n1; walk != NULL; walk = walk->next)
        printf("%d ", walk->data);
    printf("\n");

    return 0;
}

Output

9 + 4 = 13
9 - 4 = 5
9 * 4 = 36
List: 1 2 3
  • BinaryOp ops[3] reads naturally: "an array of 3 binary operations".
  • Node keeps the tag struct node so the next pointer can refer to its own type.

typedef vs #define

Pointtypedef#define
Handled byCompilerPreprocessor (text replacement)
Works forTypes onlyAny text (values, types, code)
ScopeFollows normal scope rulesFrom the line onwards, ignores scope
SemicolonEnds with ;No semicolon
Pointer aliasesCorrect for every variableCan go wrong (see below)
typedef int *IntPtr;
#define INTPTR int *

IntPtr a, b;     /* a and b are both int *            */
INTPTR c, d;     /* becomes: int * c, d;  -> d is int! */

This classic trap is why typedef is preferred for type names.

Important Points to Remember

  • typedef creates an alias, not a new type.
  • Rule: write a declaration, put typedef in front.
  • typedef struct {...} Student; removes the need to write struct.
  • Self-referential structs must use the tag inside: struct node *next.
  • Great for function pointers and portable sizes (size_t, time_t).
  • Prefer typedef over #define for types (pointer trap).

Common Mistakes Beginners Make

MistakeWhat happensFix
typedef Student struct {...};Syntax errortypedef struct {...} Student;
Using Node *next inside its own typedefError: Node not yet definedstruct node *next
Thinking typedef changes printf formatWrong outputUse the format of the real type
#define PTR int * then PTR a, b;b is a plain intUse typedef
Forgetting the semicolon after typedefCompile errorEnd with ;

typedef Practice Questions

  1. What does typedef do? Does it create a new data type?
  2. Write a typedef so that Matrix m; declares a 3 × 3 int array.
  3. Write a typedef for a pointer to a function taking a float and returning void.
  4. Why does a self-referential structure need its tag even with typedef?
  5. Give two differences between typedef and #define.
Show answers
  1. It gives an existing type a new name (alias). No new type is created.
  2. typedef int Matrix[3][3];
  3. typedef void (*FloatFn)(float);
  4. Inside the braces, the typedef name doesn't exist yet, so the member must refer to struct tag.
  5. typedef is handled by the compiler and only for types; #define is text replacement by the preprocessor. typedef handles pointer aliases correctly for every variable; #define doesn't.

Coding Exercise

Create typedef struct { int x, y; } Point; and a function Point midpoint(Point a, Point b). Print the midpoint of (2, 4) and (8, 10).

Show solution
#include <stdio.h>

typedef struct { int x, y; } Point;

Point midpoint(Point a, Point b)
{
    Point m;
    m.x = (a.x + b.x) / 2;
    m.y = (a.y + b.y) / 2;
    return m;
}

int main(void)
{
    Point p = {2, 4}, q = {8, 10};
    Point m = midpoint(p, q);
    printf("Midpoint = (%d, %d)\n", m.x, m.y);
    return 0;
}
Midpoint = (5, 7)

Quick Quiz: typedef in C (MCQ)

  1. typedef is used to:

    A) Create a new data type   B) Give an alias to an existing type   C) Define a constant   D) Allocate memory

  2. After typedef int *IP; IP a, b;, b is:

    A) int   B) int *   C) int **   D) Error

  3. After #define IP int * and IP a, b;, b is:

    A) int   B) int *   C) Error   D) float

  4. Correct syntax:

    A) typedef Point struct {int x;};   B) typedef struct {int x;} Point;   C) struct typedef Point {int x;};   D) typedef {int x;} struct Point;

  5. Which is a typedef name from the standard library?

    A) int   B) size_t   C) char   D) return

Show answers
  1. B: an alias.
  2. B: int *.
  3. A: int (text replacement gives int * a, b;).
  4. B.
  5. B: size_t.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

typedefCreates an alias, not a new type
Syntaxtypedef existing_type new_name;
Rule of thumbDeclaration + typedef in front
Struct aliastypedef struct {...} Student;
Self-referentialUse struct tag * inside
vs #definetypedef = compiler; #define = text replacement

Frequently asked questions

What is typedef in C?
A keyword that gives an existing type a new name to make code shorter and clearer.
What is the difference between typedef and #define?
typedef is handled by the compiler for types; #define is preprocessor text replacement and can break pointer declarations.
Why use typedef with structures?
So you can write Student s instead of struct student s.

Remember

  • typedef = nickname (Raju), same person.
  • Types → typedef; constants → #define.

Next Topic

Next lesson: Enumeration (enum) in C. You will give names to integer constants with enum.