This article is a continuation of the Series on the C programming tutorial and carries the discussion on C language programming and its implementation. It aims to provide easy and practical examples for understanding the C program. In our last article, we have seen the difference between the macro and inline functions in C programming. In this article, we are going to explain typedef in C Programming.
Typedef in C
Although typedef is thought of as being a storage class, it isn’t really. It allows you to introduce synonyms for types that could have been declared some other way.
In C programming, the typedef
keyword is used to create user-defined data types. It allows programmers to assign an alternative name (alias) to existing data types, making the code more readable and manageable. Here’s the basic syntax for typedef
:
typedef existing_data_type new_data_type;
For example, let’s say we have a structure called Person
that stores information about a person:
struct Person { char name[50]; int age; };
To create an alias for this structure using typedef
, we can do:
typedef struct Person Person;
Now, we can use Person
as a new data type instead of struct Person
. Here’s an example of how it can be used:
struct Person { char name[50]; int age; }; typedef struct Person Person; int main() { Person p1; // Declaring a variable of type Person strcpy(p1.name, "John Doe"); p1.age = 25; printf("Name: %s\n", p1.name); printf("Age: %d\n", p1.age); return 0; }
By using typedef
, we simplify the code by directly referring to Person
instead of struct Person
.
The new name becomes equivalent to the type that you wanted, as this example shows.
typedef int aaa, bbb, ccc; typedef int ar[15], arr[9][6]; typedef char c, *cp, carr[100]; /* now declare some objects */ /* all ints */ aaa int1; bbb int2; ccc int3; ar yyy; /* array of 15 ints */ arr xxx; /* 9*6 array of int */ c ch; /* a char */ cp pnt; /* pointer to char */ carr chry; /* array of 100 char */
In our next article, Enum in C programming.
You can also read the below tutorials.
Embedded Software | Firmware | Linux Devic Deriver | RTOS
Hi, I am a tech blogger and an Embedded Engineer. I am always eager to learn and explore tech-related concepts. And also, I wanted to share my knowledge with everyone in a more straightforward way with easy practical examples. I strongly believe that learning by doing is more powerful than just learning by reading. I love to do experiments. If you want to help or support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning!