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:-
1 |
typedef existing_type new_name; |
It is easy to create alias, put the typedef keyword followed by the existing type name and the new name for that type.
Example:-
1 2 |
typedef int my_type; my_type var1, var2, var3; |
Here, we have created the alias for integer data type as my_type, now my_type behaves same as an integer.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/* C++ typedef - Example Program of typedef in C++ */ #include <iostream> using namespace std; int main() { typedef int integer; /* now you can easily use integer to create * variables of type int like this */ integer num1, num2, sum; cout<<"W3Adda - C++ typedef Example"<<endl; cout<<"Enter two number: "; cin>>num1>>num2; sum=num1+num2; cout<<"Sum = "<<sum; return 0; } |
Output:-
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
1 2 3 4 5 6 |
struct student{ int id; char *name; float percentage; }; struct student a,b; |
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
1 2 3 4 5 6 |
typedef struct{ int id; char *name; float percentage; }student; student a,b; |
this way typedef make your declaration simpler.
typedef with union
1 2 3 4 5 6 |
typedef union{ int id; char *name; float percentage; }student; student a,b; |
typedef with enum
1 2 |
typedef enum {sun, mon, tue, wed, thu, fri, sat} weekday; weekday day1; |