C typedef
typedef gives a new name (alias) to an existing data type. It does not create a new type. It only makes the code shorter and easier to read.
Simple typedef
#include <stdio.h>
typedef unsigned int uint;
int main(void) {
uint count = 42;
printf("%u\n", count);
return 0;
}
Output:
Output of the above program is
42
typedef with struct
Without typedef we must write struct Student each time. With typedef we write only Student.
#include <stdio.h>
typedef struct {
int roll;
char name[20];
} Student;
int main(void) {
Student s = {1, "Robin"};
printf("%d %s\n", s.roll, s.name);
return 0;
}
Output:
Output of the above program is
1 Robin
typedef for a function pointer
#include <stdio.h>
typedef int (*Operation)(int, int);
int add(int a, int b) { return a + b; }
int main(void) {
Operation op = add;
printf("%d\n", op(2, 3));
return 0;
}
Output:
Output of the above program is
5
Benefits
- Shorter names for long types.
- The code is easier to change. If you change
typedef int Score;totypedef float Score;, all variables of type Score change. - Better names that explain the meaning of a variable.
Note:
typedef is not the same as #define. typedef is handled by the compiler and respects types and scope. #define is only a text replace.
Next: C enum.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |