简体   繁体   English

将联合放在c的结构中是什么意思?

[英]What does it mean by putting a union inside a struct in c?

I'm reading some c codes and find that some struct contains a union name without a variable name, just as the following example: 我正在阅读一些C代码,发现某些结构包含一个不带变量名的联合名称,如以下示例所示:

typedef union Lock Lock;

union Lock{
    uint32 key;
};

struct Test{
    Lock;
    uint32 name1;
};

What does the Lock inside Test mean? 测试中的锁定是什么意思? PS. PS。 the type uint32 has already been defined before the two declaration. 在两个声明之前已经定义了uint32类型。

What you posted isn't valid C. As far as the language is concerned, Lock and union Lock are completely different things and that's that. 您发布的内容不是有效的C。就语言而言, Lockunion Lock是完全不同的东西,仅此而已。

If however you were to say union Lock inside the struct it would compile but wouldn't do anything: it would be just a superfluous declaration declaring nothing. 但是,如果您要说在结构内部使用Union union Lock ,它将编译但不执行任何操作:这只是多余的声明,什么也没声明。


There's some speculation that adding a union Lock or Lock at the beginning of the struct does something. 有人猜测在结构的开头添加union LockLock会有所作为。 A quick check should prove that false: 快速检查应证明是错误的:

printf("%zu\n", offsetof(struct Test, name1)); /* Will print 0. */

If you can compile your code, I guess you are using an old compiler or a compiler which still supports implicit int . 如果可以编译代码,我猜您正在使用旧的编译器或仍支持隐式int的编译器。 This would mean that the compiler interprets your code as 这意味着编译器将您的代码解释为

struct Test{
    int Lock;
    uint32 name1;
}

Please see also Why does/did C allow implicit function and typeless variable declarations? 另请参阅C为什么/为什么C允许隐式函数和无类型变量声明?

So, with typedef added, gcc produces warning: 因此,添加typedef后,gcc会产生警告:

main.c:8:9: warning: declaration does not declare anything [enabled by default]

Also, simple sizeof reveals that these have same size: 同样,简单的sizeof揭示了它们具有相同的大小:

struct Test{
    Lock;
    uint32 name1;
};

struct Test2{
    uint32 name1;
};

I don't think in C there is any scenario, where this can mean anything useful. 我认为在C中没有任何情况可以表示任何有用的情况。 Maybe it is a confused attempt at forward declaration . 也许这是对前向声明的困惑尝试。

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

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