C typedef
typedef in C creates an alternate name for an existing type. It does not create a new kind of value; it gives a type a shorter or clearer name.
You will often see typedef used with structures, because it can remove repeated struct keywords from variable and function declarations.
Basic Syntax
The general form is typedef existing_type new_name;. After the declaration, you can use new_name anywhere you would use the original type.
#include <stdio.h>
typedef unsigned int Score;
int main(void)
{
Score points = 95;
printf("Score: %u\n", points);
return 0;
}
Output:
Score: 95
Here, Score is another name for unsigned int. The variable points behaves exactly like an unsigned int, including using the %u format specifier with printf.
typedef With Structures
Without typedef, a structure variable is declared with the full type name, such as struct Point p;. With typedef, you can give that structure type a shorter name.
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
int main(void)
{
Point start = {3, 4};
Point end = {8, 10};
printf("Start: (%d, %d)\n", start.x, start.y);
printf("End: (%d, %d)\n", end.x, end.y);
return 0;
}
Output:
Start: (3, 4)
End: (8, 10)
The typedef struct { ... } Point; declaration defines a structure shape and gives it the alias Point. After that, Point start; is enough to declare a variable of that structure type.
Named Struct Plus Alias
You can also keep the structure tag and add a typedef alias. This is useful when a structure needs to refer to its own type through a pointer, or when you want both names available.
#include <stdio.h>
typedef struct Employee {
int id;
double hourly_rate;
} Employee;
double weekly_pay(Employee worker, double hours)
{
return worker.hourly_rate * hours;
}
int main(void)
{
Employee dev = {101, 32.50};
printf("Employee %d earns $%.2f\n", dev.id, weekly_pay(dev, 40.0));
return 0;
}
Output:
Employee 101 earns $1300.00
In this example, struct Employee is the tagged structure type, and Employee is the alias. Most code can use the shorter Employee name, including the parameter of weekly_pay.
What typedef Does Not Do
A typedef name is only an alias. It does not add validation, limit values, or create a separate type that C treats as incompatible with the original type.
For example, if typedef int UserId; and typedef int ProductId; are declared, both aliases still represent int. C will allow assignments between them unless your own program logic prevents it.
When To Use typedef
- Use
typedefwhen it makes a type name shorter and clearer. - It is especially common with
struct,union, andenumtypes. - Choose meaningful aliases such as
Point,Employee, orScore. - Avoid hiding simple types behind vague names that make code harder to understand.
- Remember that
typedefcreates a name, not a variable.
The key idea is that typedef helps you name types in a readable way. It is most useful when it makes structure-heavy code easier to write and easier to scan.
