The typedef or “type definition” is a keyword in C or C++ Programming language that allows declaring different names for data types such as int or char. It specifies that that the declaration is a typedef declaration rather than a variable or function declaration. In C/C++, any valid data type can be aliased so that it can be referred to with a different identifier.
Another syntax to define type definitions was introduced in the C++ language recently, which uses the keyword using.
The typedef syntax
C uses the following syntax to crate data type definitions. Same syntax is inherited by C++ that uses the typedef keyword:
typedef type_name new_type_name;
Here are some of the examples of “type definitions” of existing data types into new types.
typedef char ch; typedef unsigned long ulong; typedef unsigned int size_t;
The using keyword syntax
The second syntax to define type aliases was introduced in the C++ 11. There is no difference between a type alias declaration and typedef declaration. So, all of the above type definitions can be defined as:
using ch = char; using ulong = unsigned long; using size_t = unsigned int;
Benefits of using typedef
None the keywords i.e. typedef or using creates a new distinct data types instead create a synonyms of existing data types.
They are useful to write abstract programs by eliminating underlying data types they use.
Typedef names are scope restricted i.e. they are only available inside the function or class definitions where they are declared.
Typedef make it much easier for C/C++ programmer to make changes in the code. For example, a variable type can be easily changed from int to long when using typedef.
Type definition is used to reduce the confusion in data type names by creating familiar data type names.
For example, template type names in C++ can be very long and frustrating to type. This is more evident when your C++ program makes use of Standard Template Library or other template libraries.
If you have a map of strings to ints, you could declare it as:
std::map <string, int>
Using a teypedef can help you define it in a more meaningful way as well as reduce the typing and coding mistake which you could do by using the full data type. So, you could write it as
typedef std::map<string, int> marks_list;
Now marks_list is quite easy to use and has clear meanings. Further, you can change the data type any time throughout your code. If you want marks to be a floating number or just a grade, you can easily change it as below with a single line of change in your code.
typedef std::map<string, float> marks_list; typedef std::map<string, char> marks_list;
In summary typedef helps you write C/C++ code easily and reduces the typing mistakes. It makes the code more clear and easy to modify in future.