我见过许多由如下结构组成的程序
typedef struct
{
int i;
char k;
} elem;
elem user;
为什么如此频繁地需要它?有什么具体原因或适用领域吗?
我见过许多由如下结构组成的程序
typedef struct
{
int i;
char k;
} elem;
elem user;
为什么如此频繁地需要它?有什么具体原因或适用领域吗?
当前回答
使用typedef可以避免每次声明该类型的变量时都要写struct:
struct elem
{
int i;
char k;
};
elem user; // compile error!
struct elem user; // this is correct
其他回答
您(可选地)给结构的名称称为标记名称,正如前面所指出的,它本身并不是一个类型。要获得该类型,需要使用结构体前缀。
除了GTK+,我不确定tagname是否像struct类型的typedef一样常用,所以在c++中,这是可以识别的,你可以省略struct关键字,并使用tagname作为类型名:
struct MyStruct
{
int i;
};
// The following is legal in C++:
MyStruct obj;
obj.i = 7;
在C99中,typedef是必需的。它已经过时了,但是很多工具(比如HackRank)使用c99作为它的纯C实现。这里需要typedef。
我不是说他们应该改变(也许有两个C选项),如果要求改变,我们这些在网站上学习面试的人将是SOL。
使用typedef可以避免每次声明该类型的变量时都要写struct:
struct elem
{
int i;
char k;
};
elem user; // compile error!
struct elem user; // this is correct
Typedef不会提供一组相互依赖的数据结构。你不能用typdef做到这一点:
struct bar;
struct foo;
struct foo {
struct bar *b;
};
struct bar {
struct foo *f;
};
当然你还可以加上:
typedef struct foo foo_t;
typedef struct bar bar_t;
这到底有什么意义?
摘自Dan Saks的一篇旧文章(http://www.ddj.com/cpp/184403396?pgno=3):)
The C language rules for naming structs are a little eccentric, but they're pretty harmless. However, when extended to classes in C++, those same rules open little cracks for bugs to crawl through. In C, the name s appearing in struct s { ... }; is a tag. A tag name is not a type name. Given the definition above, declarations such as s x; /* error in C */ s *p; /* error in C */ are errors in C. You must write them as struct s x; /* OK */ struct s *p; /* OK */ The names of unions and enumerations are also tags rather than types. In C, tags are distinct from all other names (for functions, types, variables, and enumeration constants). C compilers maintain tags in a symbol table that's conceptually if not physically separate from the table that holds all other names. Thus, it is possible for a C program to have both a tag and an another name with the same spelling in the same scope. For example, struct s s; is a valid declaration which declares variable s of type struct s. It may not be good practice, but C compilers must accept it. I have never seen a rationale for why C was designed this way. I have always thought it was a mistake, but there it is. Many programmers (including yours truly) prefer to think of struct names as type names, so they define an alias for the tag using a typedef. For example, defining struct s { ... }; typedef struct s S; lets you use S in place of struct s, as in S x; S *p; A program cannot use S as the name of both a type and a variable (or function or enumeration constant): S S; // error This is good. The tag name in a struct, union, or enum definition is optional. Many programmers fold the struct definition into the typedef and dispense with the tag altogether, as in: typedef struct { ... } S;
这篇链接的文章还讨论了不需要类型定义的c++行为是如何导致微妙的名称隐藏问题的。为了防止这些问题,在c++中对类和结构进行类型定义也是一个好主意,尽管乍一看似乎没有必要。在c++中,有了类型定义,隐藏的名称就变成了编译器告诉你的错误,而不是潜在问题的隐藏来源。