繁体   English   中英

什么时候在c中使用typedef?

[英]When to use typedef in c?

谁能告诉我什么时候在C中使用typedef? 在下面的代码中,我收到了gcc的警告:

warning: useless storage class specifier in empty declaration

typedef struct node
{
  int data;
  struct node* forwardLink;
} ;

typedef的语法是typedef <type> <name> ; 它使类型可以通过name访问。 在这种情况下,您只指定了一个type ,而没有指定name ,因此您的编译器会抱怨。

你可能想要

typedef struct node
{
  int data;
  struct node* forwardLink;
} node;

所以..

你可以这样做:

struct node {
  int data;
  struct node* forwardLink;
};

定义可用作struct node的对象。

像这样:

struct node x;

但是,假设您想将其称为node 然后你可以这样做:

struct node {
  int data;
  struct node* forwardLink;
};

typedef struct node node;

要么

 typedef struct {
  int data;
  void* forwardLink;
} node;

然后将其用作:

node x;

如果要为类型使用其他名称(例如结构),请使用typedef

在你的情况,而不是使用struct node来声明一个变量,你可以使用,而不是仅仅Node ,为的别名struct node

但是你在声明中遗漏了别名:

typedef struct node
{
  int data;
  struct node* forwardLink;
} Node;

这可以完成同样的事情,但可能更好地说明您的错误原因:

struct node
{
  int data;
  struct node* forwardLink;
};

// this is equivalent to the above typedef:
typedef struct node Node;
typedef struct node
{
    int data;
    struct node* forwardLink;
} MyNode;

如果你想写

MyNode * p;

代替

struct node *p;

在struct中,你仍然需要struct node * forwardLink;

Typedef用于定义用户数据类型。 例如

typedef int integer;

现在您可以使用integer来定义int数据类型而不是int。

integer a;// a would be declared as int only

对于某些变量的可能值列表:

typedef enum {BLACK=0, WHITE, RED, YELLOW, BLUE} TColor;

一般来说,它可以帮助您了解您是否正确操作事物,因为编译器会警告您隐式转换等等。 它比使代码更具可读性更有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM