In this tutorial we will introduce you to typedef, and explain the reason and usage of “typedef struct” that is commonly seen in C code.
Why do we use typedef in C?
The usage of typedef is purely for aesthetic purposes, and ease of writing. It doesn’t actually bring in new functionality or anything.
Normally, when creating a struct in C, we do the following.
struct Vector {
int x;
int y
};
int main() {
struct Vector v1 = {4, 5};
return 0;
}
Some people may not want to have to write the “struct” part every time you create a new struct variable. So in order to resolve this problem, we use typedef.
Note: typedef is a keyword used to create aliases or an alternate name for a datatype. It’s uses are not limited to just structs, but can be used in many other places as well. To learn more about it, check out our typedef tutorial.
How to use typedef in C?
There are two methods through which we can implement typedef in such a way that we don’t need to write “struct” every time.
Method# 1
This method involves including “typedef” in the Struct declaration, and including the name of the Struct in between the closing curly bracket and the semi-colon.
typedef struct Vector {
int x;
int y
} Vector;
int main() {
Vector v1 = {4, 5};
return 0;
}
Method# 2
This method involves using typedef in a more standard way.
struct Vector {
int x;
int y
};
typedef struct Vector Vector;
int main() {
Vector v1 = {4, 5};
return 0;
}
In both this method and the previous one, “struct Vector” is being given the alias “Vector”. So later when you use “Vector” to create a struct variable, the compiler knows that you mean to say “struct Vector”.
This marks the end of the “How (and why) to use typedef struct in C” Tutorial. Any suggestions or contributions are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.
Great, Thanks for the help. Very clear explanation!