Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 8, 2021 06:45 am GMT

Quick Introduction to typedef in C

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 youve to use repetitively throughout your code.

// Examplesunsigned 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> PRODUCTPRODUCT 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. Whats 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 typepSTRUCT 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 youll 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 youd 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


Original Link: https://dev.to/guptaaastha/quick-introduction-to-typedef-in-c-5362

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To