In C, we have an option to set any other name for a specific data type. For doing that we use a keyword called "typedef". In this article, I'll be explaining how typedef works and how you can use it in your own code.
Example
Suppose you have to set the name of a certain data type to some other name (there could be any reason for but mostly used for getting a better understanding of the code as it makes the code more readable). For instance, you want to name "int" as "number", then you can simply use the following code for that:
typedef int number;
Syntax
To apply typedef, you simply need to follow this syntax:
"typedef
Another example could be:
#include <stdio.h>
int main(){
typedef char alphabet;
alphabet a;
printf("Enter an alphabet: ");
scanf("%c", &a);
printf("The alphabet you entered is: %c\n", a);
}
Here, we've changed the name of "char" datatype to "alphabet". After that you can simply use "alphabet" to declare "char" variables, like how we've done for variable "a".
Using typedef for struct
Typedef is mainly used for naming structures and unions. Declaring variables of struct type is a lengthy process. Like:
#include <stdio.h>
struct name{
char first_name[20];
char last_name[20];
};
int main(){
struct name my_name;
}
In the above example, whenever you want to declare a variable of type "struct name" you'll always have to write "struct name" in declaration of the variable. Instead of writing the whole thing we can simply just use typedef for it. You can do that like this:
#include <stdio.h>
typedef struct name{
char first_name[20];
char last_name[20];
}NAME;
int main(){
NAME my_name;
}
In this way, the code looks much simpler and whenever you want to delcare a variable of type "struct name", you can just simply type in "NAME" for that. It comes handy specially when you're writing lengthy codes.
Conclusion
This is all about typedef keyword in C. I hope you got to learn something new from this article. Thanks for reading!
For reading more such articles you can visit my page here.
Comments (0)