Lesson 95 +10 XP

typedef

typedef

typedef creates an alias - a new name for an existing type, so code reads better.

Aliasing a type

typedef unsigned long ulong;
ulong counter = 0;

Now ulong means unsigned long.

The classic struct pattern

Without typedef you write struct Person everywhere:

struct Person {
    char name[50];
    int age;
};
struct Person p1;

With typedef:

typedef struct {
    char name[50];
    int age;
} Person;

Person p1;

Reading typedef

typedef <type> <alias>; says "alias is another name for type".

TL;DR

  • typedef gives a type a new, shorter name.
  • typedef unsigned long ulong;.
  • For structs it removes the struct keyword.
  • Better readability, no behavior change.