简体   繁体   English

带有 typedef 并声明 function 的结构

[英]struct with typedef and declaring a function

When creating a struct you can do创建结构时,您可以执行

struct name {
 ...
} var1, var2;

to create variables of type struct name.创建结构名称类型的变量。

if you want to do typedef the syntax is typedef <existing type> <alias>如果你想做 typedef 语法是 typedef <existing type> <alias>

to do a typedef for a struct type you do为你做的结构类型做一个 typedef

typedef struct name(optional) {
 ...
} Typename;

where typename is the alias and the struct part is the existing type.其中 typename 是别名,struct 部分是现有类型。

I am wondering if you can combine the above code sections.我想知道你是否可以结合上面的代码部分。 ex do a typedef on a struct like in the second example and in the same line declare var1 and var2 like we did for the first example. ex 在第二个示例中的结构上执行 typedef 并在同一行中声明 var1 和 var2 就像我们在第一个示例中所做的那样。 this doesnt seem possible since the Typename seems to take the place of var1 and var2这似乎不可能,因为 Typename 似乎取代了 var1 和 var2

No, not possible.不,不可能。 There is no syntax for that.没有语法。


Tangentially related, what is possible is having anonymous struct:切向相关的是,可能有匿名结构:

struct {
    ...
} var1, var2;

As a side note, the problem is circumvented by not adding typedefs for structs.作为旁注,通过不为结构添加类型定义来规避该问题。

In a more general note, code is easier to understand, if each statement does one thing (like define a variable or define a type).在更一般的注释中,如果每个语句都做一件事(例如定义变量定义类型),则代码更容易理解。 So even if this was possible, doing wouldn't necessarily be a good idea.所以即使这是可能的,做也不一定是一个好主意。

You cannot do that because typedef is synthetically an "storage-class specifier" like static , extern , auto , register and _Threadlocal .您不能这样做,因为typedef综合起来是一个“存储类说明符”,例如staticexternautoregister_Threadlocal As result it is not possible to have no storage qualifier (default one) and typedef at the same time.因此,不可能同时没有存储限定符(默认一个)和typedef However, one can do achieve the desired effect by placing typedef below definition of var1 and var2 object.但是,可以通过将typedef放在var1var2 object 的定义下方来达到预期的效果。

struct name {
 ...
} var1, var2;

typedef struct name Typename;

The upcoming C23 standard will support typeof which would let one create aliases for untagged structs.即将到来的 C23 标准将支持typeof ,它允许为未标记的结构创建别名。

struct  {
 ...
} var1, var2;

typedef typeof(var1) Typename;

The typeof is already supported by many compilers (gcc, clang, icc) with an exception of infamous MSVC.除了臭名昭著的 MSVC,许多编译器(gcc、clang、icc)已经支持typeof

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

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