Course contentsShow
← C
Lesson 607 of 1,2199. Structures and UnionsFree lesson

The syntax of typedef

The syntax of typedef

What you'll learn: How to use the typedef keyword to create shorter, more readable nicknames for existing C data types.

The Nickname Rule

In C, some type names can get long and repetitive, especially when working with structures. The typedef keyword is a tool that lets you create an alias—a nickname—for any existing type. It doesn’t create a new type of data; it simply gives an old type a new name that is easier to type.

Think of it like a legal name versus a nickname. If a friend's legal name is "Jonathan Christopher Bartholomew III," you might use a typedef to simply call him "Jon." Whenever you say "Jon," everyone knows you are actually referring to the full legal entity.

How to Write It

The syntax for typedef often confuses beginners because it looks like a variable declaration. To master it, follow this mental template:

  1. Start with the keyword typedef.
  2. Write the original type (the "legal name").
  3. Write the new name (the "nickname").
  4. End with a semicolon.
#include <stdio.h>

// 1. Alias a primitive type
typedef unsigned char byte;

// 2. Alias a structure (the most common use)
typedef struct {
    int x;
    int y;
} Point;

int main() {
    // Instead of 'unsigned char', we use 'byte'
    byte level = 255;

    // Instead of 'struct Point', we use 'Point'
    Point player_pos = {10, 20};

    printf("Level: %d, Position: %d, %d", level, player_pos.x, player_pos.y);
    return 0;
}

Why Use It?

The most powerful use of typedef is with struct. Normally, every time you want to create a variable from a structure, you have to type the word struct before the name (e.g., struct User user1;). By using typedef, you can hide that requirement and treat your structure just like a standard type (e.g., User user1;).

This makes your code much cleaner and easier to scan. However, remember the golden rule: typedef is just a label. Under the hood, the C compiler still treats your nickname as the original type.

Key takeaway

Use typedef [original type] [new name]; to create a shorter alias for complex types to make your code more readable.