C语言 typedef 有什么用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2566027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:02:21  来源:igfitidea点击:

What is the use of typedef?

ctypedef

提问by hks

What is the use of typedef keyword in C ? When is it needed?

C 中 typedef 关键字的用途是什么?什么时候需要?

回答by T.J. Crowder

typedefis for defining something as a type. For instance:

typedef用于将某物定义为type。例如:

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

...defines THINGYas the given struct. That way, you can use it like this:

...定义THINGY为给定的结构。这样,您可以像这样使用它:

THINGY t;

...rather than:

...而不是:

struct _THINGY_STRUCT {
  int a;
  int b;
};

struct _THINGY_STRUCT t;

...which is a bit more verbose. typedefs can make some things dramaticallyclearer, specially pointers to functions.

......这有点冗长。类型定义可以做一些事情极大地更清晰,特别是函数指针。

回答by Oded

From wikipedia:

来自维基百科:

typedef is a keyword in the C and C++ programming languages. The purpose of typedef is to assign alternative names to existing types, most often those whose standard declaration is cumbersome, potentially confusing, or likely to vary from one implementation to another.

typedef 是 C 和 C++ 编程语言中的关键字。typedef 的目的是为现有类型分配替代名称,通常是那些标准声明繁琐、可能令人困惑或可能因一种实现而异的类型。

And:

和:

K&R states that there are two reasons for using a typedef. First, it provides a means to make a program more portable. Instead of having to change a type everywhere it appears throughout the program's source files, only a single typedef statement needs to be changed. Second, a typedef can make a complex declaration easier to understand.

K&R 指出使用 typedef 有两个原因。首先,它提供了一种使程序更具可移植性的方法。不必更改出现在程序源文件中的任何地方的类型,只需更改一个 typedef 语句。其次,typedef 可以使复杂的声明更容易理解。

And an argument against:

并提出反对意见:

He (Greg K.H.) argues that this practice not only unnecessarily obfuscates code, it can also cause programmers to accidentally misuse large structures thinking them to be simple types.

他(Greg KH)认为,这种做法不仅会不必要地混淆代码,还会导致程序员误用大型结构,认为它们是简单类型。

回答by andyn

Typedef is used to create aliases to existing types. It's a bit of a misnomer: typedef does not define new types as the new types are interchangeable with the underlying type. Typedefs are often used for clarity and portability in interface definitions when the underlying type is subject to change or is not of importance.

Typedef 用于为现有类型创建别名。这有点用词不当:typedef 没有定义新类型,因为新类型可以与基础类型互换。当底层类型可能发生变化或不重要时,Typedef 通常用于接口定义中的清晰度和可移植性。

For example:

例如:

// 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 can also be used to give names to unnamed types. In such cases, the typedef will be the only name for said type:

Typedef 还可用于为未命名类型命名。在这种情况下, typedef 将是所述类型的唯一名称:

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

Naming conventions differ. Usually it's recommended to use a trailing_underscore_and_tor CamelCase.

命名约定不同。通常建议使用 atrailing_underscore_and_tCamelCase

回答by Coffee_lover

typedef doesnot introduce a new type but it just provide a new name for a type.

typedef 不会引入新类型,而只是为类型提供新名称。

TYPEDEFCAN BE USED FOR:

TYPEDEF可用于:

  1. Types that combine arrays,structs,pointers or functions.

  2. To facilitate the portability , typedefthe type you require .Then when you port the code to different platforms,select the right type by making changes only in the typedef.

  3. A typedefcan provide a simple name for a complicated type cast.

  4. typedefcan also be used to give names to unnamed types. In such cases, the typedef will be the only name for said type.

  1. 组合数组、结构、指针或函数的类型。

  2. 为了便于移植,typedef你需要的类型。然后当你将代码移植到不同的平台时,通过只在typedef中进行更改来选择正确的类型。

  3. Atypedef可以为复杂的类型转换提供一个简单的名称。

  4. typedef也可以用来给未命名的类型命名。在这种情况下,typedef 将是所述类型的唯一名称。

NOTE:-SHOULDNT USE TYPEDEFWITH STRUCTS. ALWAYS USE A TAG IN A STRUCTURE DEFINITION EVEN IF ITS NOT NEEDED.

注意:-不应TYPEDEF与结构一起使用。即使不需要,也始终在结构定义中使用标记。

回答by shaul boyer

from Wikipedia: "K&R states that there are two reasons for using a typedef. First ... . Second, a typedef can make a complex declaration easier to understand."

来自维基百科:“K&R 指出使用 typedef 有两个原因。第一......第二,typedef 可以使复杂的声明更容易理解。”

Here is an example to the second reason of using typedef, simplifying complex types (the complex type is taken from K&R "The C programming language second edition p. 136).

这是使用 typedef 的第二个原因的示例,简化复杂类型(复杂类型取自 K&R“C 编程语言第二版第 136 页)。

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

x is a function returning pointer to array[] of pointer to function returning char.

x 是一个函数,返回指向 array[] 的指针,该指针指向返回 char 的函数。

We can make the above declaration understandable using typedefs. Please see the example below.

我们可以使用 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);
}

回答by Amjad

Explaining the use of typedef in the following example. Further, Typedef is used to make the code more readable.

在下面的例子中解释了 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.
    */

回答by mirhpe danielle

typedef unsigned char BYTE;

After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example..

在此类型定义之后,标识符 BYTE 可以用作 unsigned char 类型的缩写,例如..

BYTE b1, b2;

字节 b1, b2;

回答by Thomas Bonini

It can alias another type.

它可以作为另一种类型的别名。

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