Skip to content
Search

C++:typedef

lastmod 2021-01-03created 2020-08-313 edits

Typedef function pointers

A typical function pointer looks like this:

// 파라미터를 int*로 받고, int를 return하는 함수를 가리킬 수 있는 포인터.
int (*pf)(int*);

To Typedef the above, do the following:

typedef int (*FpType)(int *);

As an application,

int (*arpf[5])(int);

This creates an array of 5 function pointers named arpf, but readability suffers, so it can be rewritten as below.

typedef int (*FpType)(int);
FpType arpf[5];

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;
}

See also

author Zer0 sitemap