T.J*_*der 53
typedef
用于将某事物定义为类型.例如:
typedef struct {
int a;
int b;
} THINGY;
Run Code Online (Sandbox Code Playgroud)
...定义THINGY
为给定的结构.这样,您可以像这样使用它:
THINGY t;
Run Code Online (Sandbox Code Playgroud)
...而不是:
struct _THINGY_STRUCT {
int a;
int b;
};
struct _THINGY_STRUCT t;
Run Code Online (Sandbox Code Playgroud)
......有点冗长.类型定义可以做一些事情极大地更清晰,特别是函数指针.
Ode*_*ded 30
来自维基百科:
typedef是C和C++编程语言中的关键字.typedef的目的是为现有类型指定替代名称,通常是那些标准声明繁琐,可能令人困惑或可能因实现而异的那些.
和:
K&R声称使用typedef有两个原因.首先,它提供了一种使程序更具可移植性的方法.不需要在程序的源文件中出现的任何地方更改类型,只需要更改单个typedef语句.其次,typedef可以使复杂的声明更容易理解.
反对的论点:
他(Greg KH)辩称,这种做法不仅会不必要地混淆代码,还会导致程序员意外滥用大型结构,认为它们是简单类型.
and*_*dyn 13
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;
Run Code Online (Sandbox Code Playgroud)
Typedef也可用于为未命名的类型指定名称.在这种情况下,typedef将是所述类型的唯一名称:
typedef struct { int i; } data_t;
typedef enum { YES, NO, FILE_NOT_FOUND } return_code_t;
Run Code Online (Sandbox Code Playgroud)
命名约定不同.通常建议使用trailing_underscore_and_t
或CamelCase
.
在下面的例子中解释了 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.
*/
Run Code Online (Sandbox Code Playgroud)