Skip to content

C++:typedef

Typedef 함수포인터

일반적인 함수포인터는 아래와 같다.

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

위의 내용을 Typedef할 경우 아래와 같이 하면 된다.

typedef int (*FpType)(int *);

응용을 하자면,

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

이렇게 할 경우 arpf라는 함수포인터 배열 5개가 생성되지만 가독성이 떨어지므로 아래와 같이 수정할 수 있다.

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

typedef struct 를 사용하는 이유?

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

위의 경우, Point 구조체를 사용하고 싶을 경우 struct Point라고 써야 한다.

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

위의 경우, Point 구조체를 struct 없이 바로 사용할 수 있다.

3. typedef struct를 한번에 사용할 수 있다:

#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