C++:typedef
lastmod 2021-01-03created 2020-08-313 edits
Typedef function pointers
A typical function pointer looks like this:
To Typedef the above, do the following:
As an application,
This creates an array of 5 function pointers named arpf, but readability suffers, so it can be rewritten as below.
Why use typedef struct?
1. Without typedef:
#include<stdio.h>
struct Point{
int x;
int y;
};
int main() {
struct Point p1;
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}
In this case, to use the Point struct you must write struct Point.
2. With typedef:
#include<stdio.h>
struct Point{
int x;
int y;
};
typedef struct Point Point;
int main() {
Point p1;
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}
In this case, the Point struct can be used directly without struct.
3. typedef struct can be used in one go:
#include<stdio.h>
typedef struct Point{
int x;
int y;
} Point;
int main() {
Point p1;
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}