typedef
- C course
- Beginner
- Lesson 11/116
- 4 min
Learn to give new names to types with typedef.
Aliases with typedef
The typedef keyword gives a new name to an existing type. It is used to shorten long type names and make code more meaningful:
typedef unsigned int uint;
typedef double Distance;Now uint and Distance can be used just like unsigned int and double. The compiler treats them the same; only readability improves.
typedef vs #define
typedef and #define look similar but work differently:
- typedef: gives a type a new name at compile time
- #define: performs text substitution; no type checking
Always prefer typedef for type aliases. #define is for constant values; it lacks type context and is error-prone.
Practice Use typedef
Define typedef double Distance;. Declare a Distance variable (5.5 for example) and print it with printf using %lf.
Starter code
#include <stdio.h>
// add typedef
int main(void) {
// declare Distance variable and print
return 0;
}Sample solution
#include <stdio.h>
typedef double Distance;
int main(void) {
Distance d = 5.5;
printf("%lf", d);
return 0;
}Expected output
5.500000
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 After typedef unsigned int uint; what is uint?
- A function
- A new primitive type
- A variable name
- An alias for unsigned int Correct answer
Explanation: uint is an alias for the unsigned int type.
2 typedef name
typedef double ____;
typedef double Distance;
Explanation: Distance becomes an alias for double. Type names start with uppercase.
3 Match typedef concepts
| Term | Meaning |
|---|---|
typedef |
Type alias |
unsigned |
Without sign |
int |
Integer |
struct |
Composite |