C++ typedef

In this tutorial you will learn about the C++ typedef and its application with practical example.

C++ typedef

In C++, typedef ( type definition ) is a keyword allows us to create an alias for existing data types. Once, we have created a type definition, then we can declare a variable using the alias we created. This alias is equivalent to the data type for which it is created. Remember that, in addition to the type definition or alias we are always free to use the original keyword to define variable of any data type.

Syntax:-

It is easy to create alias, put the typedef keyword followed by the existing type name and the new name for that type.

Example:-

Here, we have created the alias for integer data type as my_type, now my_type behaves same as an integer.

Example:-

Output:-

cpp_typedef_example

Advantages of typedef

  • It makes the program more portable.
  • typedef make complex declaration easier to understand.
  • It can make your code more clear
  • It can make your code easier to modify

typedef with a struct

Take a look at below structure declaration

As we can see we have to include keyword struct every time you declare a new variable, but if we use typedef then the declaration will as easy as below

this way typedef make your declaration simpler.

typedef with union

typedef with enum

In this tutorial we have learn about the C++ typedef and its application with practical example. I hope you will like this tutorial.