programing

typedef의 사용은 무엇입니까?

nasanasas 2021. 1. 11. 08:20
반응형

typedef의 사용은 무엇입니까?


C에서 typedef 키워드의 사용은 무엇입니까? 언제 필요합니까?


typedef무언가를 유형 으로 정의하기위한 것 입니다. 예를 들면 :

typedef struct {
  int a;
  int b;
} THINGY;

... THINGY주어진 구조체로 정의합니다 . 이렇게하면 다음과 같이 사용할 수 있습니다.

THINGY t;

... 보단 :

struct _THINGY_STRUCT {
  int a;
  int b;
};

struct _THINGY_STRUCT t;

... 좀 더 장황합니다. typedef는 특히 함수에 대한 포인터와 같은 일부를 훨씬 더 명확하게 만들 수 있습니다 .


wikipedia에서 :

typedef는 C 및 C ++ 프로그래밍 언어의 키워드입니다. typedef의 목적은 기존 유형에 대체 이름을 할당하는 것입니다. 대부분의 경우 표준 선언이 번거 롭거나 혼란 스럽거나 구현마다 다를 수있는 유형입니다.

과:

K & R은 typedef를 사용하는 데는 두 가지 이유가 있다고 말합니다. 첫째, 프로그램의 이식성을 높이는 수단을 제공합니다. 프로그램의 소스 파일 전체에 나타나는 모든 곳에서 유형을 변경하는 대신 단일 typedef 문만 변경하면됩니다. 둘째, typedef는 복잡한 선언을 이해하기 쉽게 만들 수 있습니다.

그리고 반대 :

그 (Greg KH)는 이러한 관행이 코드를 불필요하게 난독화할뿐만 아니라 프로그래머가 실수로 큰 구조를 단순한 유형으로 생각하는 오용하게 만들 수 있다고 주장합니다.


Typedef는 기존 유형에 대한 별칭 을 만드는 데 사용됩니다 . 약간 잘못된 이름입니다 . typedef는 새 유형이 기본 유형과 상호 교환 될 수 있으므로 새 유형을 정의하지 않습니다. Typedef는 기본 유형이 변경되거나 중요하지 않을 때 인터페이스 정의의 명확성과 이식성을 위해 자주 사용됩니다.

예를 들면 :

// Possibly useful in POSIX:
typedef int filedescriptor_t;

// Define a struct foo and then give it a typedef...
struct foo { int i; };
typedef struct foo foo_t;

// ...or just define everything in one go.
typedef struct bar { int i; } bar_t;

// Typedef is very, very useful with function pointers:
typedef int (*CompareFunction)(char const *, char const *);
CompareFunction c = strcmp;

Typedef를 사용하여 이름이 지정되지 않은 유형에 이름을 지정할 수도 있습니다. 이러한 경우 typedef는 해당 유형의 유일한 이름입니다.

typedef struct { int i; } data_t;
typedef enum { YES, NO, FILE_NOT_FOUND } return_code_t;

명명 규칙이 다릅니다. 보통은 사용하는 것이 좋습니다 trailing_underscore_and_t또는 CamelCase.


typedef는 새 유형을 도입하지 않지만 유형에 대한 새 이름을 제공합니다.

TYPEDEF 다음 용도로 사용할 수 있습니다.

  1. 배열, 구조체, 포인터 또는 함수를 결합하는 유형.

  2. 이식성을 용이하게하기 위해 typedef필요한 유형. 그런 다음 코드를 다른 플랫폼으로 이식 할 때 typedef에서만 변경하여 올바른 유형을 선택하십시오.

  3. A typedef는 복잡한 유형 캐스트에 대한 간단한 이름을 제공 할 수 있습니다.

  4. typedef명명되지 않은 유형에 이름을 부여하는 데 사용할 수도 있습니다. 이러한 경우 typedef는 해당 유형의 유일한 이름입니다.

참고 :- 구조체 TYPEDEF와 함께 사용 해서는 안됩니다. 필요하지 않은 경우에도 구조 정의에 항상 태그를 사용하십시오.


Wikipedia에서 : "K & R은 typedef를 사용하는 데는 두 가지 이유가 있다고 말합니다. 첫째 .... 둘째, typedef는 복잡한 선언을 이해하기 쉽게 만들 수 있습니다."

다음은 typedef를 사용하여 복잡한 유형을 단순화하는 두 번째 이유에 대한 예입니다 (복합 유형은 K & R "The C programming language second edition p. 136에서 가져옴).

char (*(*x([])())

x는 char를 반환하는 함수에 대한 포인터의 array []에 대한 포인터를 반환하는 함수입니다.

typedef를 사용하여 위의 선언을 이해하기 쉽게 만들 수 있습니다. 아래 예를 참조하십시오.

typedef char (*pfType)(); // pf is the type of pointer to function returning
                          // char
typedef pfType pArrType[2];  // pArr is the type of array of pointers to
                             // functions returning char

char charf()
{ return('b');
}

pArrType pArr={charf,charf};
pfType *FinalF()     // f is a function returning pointer to array of
                     // pointer to function returning char
{
return(pArr);
}

다음 예제에서 typedef의 사용을 설명합니다. 또한 Typedef는 코드를 더 읽기 쉽게 만드는 데 사용됩니다.

#include <stdio.h>
#include <math.h>

/*
To define a new type name with typedef, follow these steps:
1. Write the statement as if a variable of the desired type were being declared.
2. Where the name of the declared variable would normally appear, substitute the new type name.
3. In front of everything, place the keyword typedef.
*/

// typedef a primitive data type
typedef double distance;

// typedef struct 
typedef struct{
    int x;
    int y;
} point;

//typedef an array 
typedef point points[100]; 

points ps = {0}; // ps is an array of 100 point 

// typedef a function
typedef distance (*distanceFun_p)(point,point) ; // TYPE_DEF distanceFun_p TO BE int (*distanceFun_p)(point,point)

// prototype a function     
distance findDistance(point, point);

int main(int argc, char const *argv[])
{
    // delcare a function pointer 
    distanceFun_p func_p;

    // initialize the function pointer with a function address
    func_p = findDistance;

    // initialize two point variables 
    point p1 = {0,0} , p2 = {1,1};

    // call the function through the pointer
    distance d = func_p(p1,p2);

    printf("the distance is %f\n", d );

    return 0;
}

distance findDistance(point p1, point p2)
{
distance xdiff =  p1.x - p2.x;
distance ydiff =  p1.y - p2.y;

return sqrt( (xdiff * xdiff) + (ydiff * ydiff) );
} In front of everything, place the keyword typedef.
    */

다른 유형의 별명을 지정할 수 있습니다.

typedef unsigned int uint; /* uint is now an alias for "unsigned int" */

typedef unsigned char BYTE;

이 형식 정의 후에 식별자 BYTE는 예를 들어 unsigned char 형식의 약어로 사용할 수 있습니다.

바이트 b1, b2;

참조 URL : https://stackoverflow.com/questions/2566027/what-is-the-use-of-typedef

반응형