C typedef Complete Tutorial

In this section, we will learn what the typedef operator is and how to use it in C.

What is C typedef?

The `typedef` is an operator that allows a programmer to create another name for a type and use that name throughout the source code.

Let’s say we want to create multiple variable of type `long long int`.

This is of course, how we would go in a typical situation:

#include <stdio.h>

int main() {

    long long int var1;
    long long int var2;
    long long int var3;

    return 0;
}

What’s the problem with this code?

Well, actually nothing! Except it’s tedious to every time create a variable with such a long type!

That’s where the `typedef` keyword can help. Basically, using the typedef operator, we can create a shorter (AKA alias) name for a data type and use that name in a program instead.

C typedef Syntax

This is how it works:

typedef real-type-name abbreviation-name;
  • `typedef`: first we use the keyword `typedef` when we want to introduce a new name for a type.
  • `real-type-name`: this is the actual type that we want to introduce another name for it.

For example: `long long int` or `long double` etc.

  • `abbreviation-name`: this is the name that we want to use instead of the name of the actual-type.

This name can be anything as long as it follows the standard rules for declaring a name in C.

Example: typedef in C

#include <stdio.h>

typedef long long int lInt;
int main() {

    lInt var1;
    lInt var2;
    lInt var3;

    return 0;
}

In this example, we’ve declared a new name for `long long int` which is `lName` and used it wherever we wanted to create a new variable of `long long int` type.

Note that there’s no-difference between using `long long int` and `lName`. Both will cause the complier to allocate the same amount of memory for the target variable.

Note: creating a new name will not replace the old one! Both are valid and can be used in the source code.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies