Chapter 27 of 37

typedef

Sometimes C data type names can become long or difficult to write, especially when working with structures, pointers, or complex types.

The typedef keyword allows us to create a new name (alias) for an existing data type.

What is typedef?

typedef is used to create an alternative name for an existing data type.

For example:

typedef int Number;

Now we can use Number instead of int:

Number age = 20;

Here, Number is simply another name for int. It does not create a new data type.


typedef with Structures

One of the most common uses of typedef is with structures.

Without typedef:

struct Student
{
    char name[20];
    int age;
};

struct Student student1;

With typedef:

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

Student student1;

Now we don't need to write struct Student every time.


typedef with Pointers

typedef can also make pointer types easier to use.

typedef int* IntPtr;

IntPtr ptr;

Here, IntPtr is an alias for int *.

So:

IntPtr ptr;

is equivalent to:

int *ptr;

Why Use typedef?

typedef can make code:

  • Shorter

  • Easier to read

  • Easier to maintain

  • More convenient when working with complex types

For example, instead of repeatedly writing:

struct Student

we can simply write:

Student

typedef vs #define

Both can create aliases, but they work differently.

typedef int Number;

is a type alias understood by the compiler.

Whereas:

#define Number int

is a preprocessor macro that performs text substitution before compilation.

For creating type aliases, typedef is the appropriate tool.

In Simple Words

typedef gives an existing data type a new name.

For example:

typedef int Number;

Now:

Number age = 20;

is simply another way of writing:

int age = 20;

Remember:

typedef → Create an alias for an existing type.