C++ is a strongly typed language which means we take types very seriously in the C++ community! While types are important and reduce bugs, it gets tiresome pretty quickly when there's an inbuilt type with a long name that you’ve to use repetitively throughout your code.
// Examples
unsigned long num;
std::pair <std::string,double> product_one;
Introducing typedef
declarations, easy effortless way to declare and use types in your file. typedef
declarations can be considered as nicknames✨ that you give to an inbuilt type and whenever you want to say inbuilt-type
, you say their nickname instead.
typedef unsigned long UL;
UL num; // Equivalent to unsigned long num;
typedef std::pair <std::string,double> PRODUCT
PRODUCT product_one("notebook",54.5);
// Equivalent to std::pair <std::string,double> ("notebook",54.5);
In contrast to the class
, struct
, union
, and enum
declarations, typedef declarations
do not introduce new types, they simply introduce new names for existing types. What’s more exciting is that you can declare any type with typedef
, including pointers, functions and array types.
typedef struct {int a; int b;} STRUCT, *p_STRUCT;
// the following two objects have the same type
pSTRUCT p_struct_1;
STRUCT* p_struct_2;
typedef
declarations are scoped, that is you can declare a variable
with the same name as of the typedef
in the same file in a different scope and you’ll face no type errors whatsoever!
typedef unsigned long UL;
int main()
{
unsigned int UL;
// re-declaration hides typedef name
// now UL is an unsigned int variable in this scope
}
// typedef UL back in scope
However, I would highly advise against this practice because it eventually makes your file less readable and more confusing which is not something you’d want to do.🤷
In summary, you can use
typedef
declarations to construct shorter and more meaningful names to the types that are already defined by the language or for the types that you have declared.
Hopefully this article gave you a brief introduction to typedef and you had fun reading it. To get more information on the topic, refer the docs here.
Thanks for giving this article a read and I'll see you in the next one 😄