是否可以(合法)在复合文字中分配匿名联合?
我有一个结构:
typedef struct _n
{
int type;
union {
char *s;
int i;
};
} n;
当我尝试分配复合文字时,例如:
node n1 = {1, 0};
node n2 = {2, "test"};
gcc 给了我一些警告,例如:
warning: initialization makes pointer from integer without a cast
warning: initialization from incompatible pointer type
嗯,很明显编译器不确定我是否只是将值分配给可能不明确的类型。但是,即使我尝试更精确地指定:
node n0 = {type: 1, i: 4};
我得到:
error: unknown field ‘i’ specified in initializer
我已经读到,如果我将 (union
放在 i:
之前,那么它可能会起作用。然而,我更喜欢有一个匿名工会。有办法做到吗?
I have a struct:
typedef struct _n
{
int type;
union {
char *s;
int i;
};
} n;
When I try to assign a compound literal, like:
node n1 = {1, 0};
node n2 = {2, "test"};
gcc gives me some warnings such as:
warning: initialization makes pointer from integer without a cast
warning: initialization from incompatible pointer type
Well, it's clear that the compiler isn't sure about me just assigning a value to a possibly ambiguous type. However, even if I try to specify more precisely:
node n0 = {type: 1, i: 4};
I get:
error: unknown field ‘i’ specified in initializer
I have read that if I put (union <union name>)
before i:
then it may work. However, I prefer having an anonymous union. Is there a way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
匿名联合不是标准 C——它们是编译器扩展。我强烈建议给工会起一个名字。如果你坚持使用匿名联合,那么你只能为它的第一个元素提供一个初始值设定项:
当使用
-Wall -Wextra -pedantic
编译时,gcc 给了我警告“初始值设定项周围缺少大括号” ”,这是一个有效的警告。初始化程序实际上应该这样指定:现在这只会给出一个警告“ISO C 不支持未命名的结构/联合”。
如果您给联合体一个名称,那么您可以使用称为“指定初始化程序”的 C99 功能来初始化联合体的特定成员:
您需要联合体有一个名称;否则,编译器会抱怨其中指定的初始值设定项。
您尝试使用的语法
node n0 = {type: 1, i: 4}
是无效语法;看起来您正在尝试使用指定的初始值设定项。Anonymous unions are not standard C -- they are a compiler extension. I would strongly recommend giving the union a name. If you insist on using an anonymous union, then you can only give an initializer for the first element of it:
When compiled with
-Wall -Wextra -pedantic
, gcc gave me the warning "missing braces around initializer", which is a valid warning. The initializer should actually be specified like this:Now this only gives a warning that "ISO C doesn't support unnamed structs/unions".
If you give the union a name, then you can use a C99 feature called designated initializers to initialize a specific member of the union:
You need the union to have a name; otherwise, the compiler will complain about the designated initializer inside it.
The syntax you were trying to use
node n0 = {type: 1, i: 4}
is invalid syntax; it looks like you were trying to use designated initializers.