为什么结构数组不需要大括号初始化?
这段代码:
#include <stdio.h>
struct
{
int i;
const char* str;
} ar[] = {
1,"asd", //should be {1, "asd"},
2, "qwe", //should be {2, "qwe"},
3, "poi" //should be {3,"poi"}
};
int main()
{
printf("%s\n", ar[2].str);
}
工作得很好,即使数组 ar
的每个元素都应该用大括号括起来(至少我希望如此)。为什么这可能?
This code:
#include <stdio.h>
struct
{
int i;
const char* str;
} ar[] = {
1,"asd", //should be {1, "asd"},
2, "qwe", //should be {2, "qwe"},
3, "poi" //should be {3,"poi"}
};
int main()
{
printf("%s\n", ar[2].str);
}
Works perfectly fine, even though each element of array ar
should enclosed in braces (I would expect that at least). Why is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
6.7.9 Initialization/20 说明此类结构元素如何已初始化:
(强调我的)
所以它是有效的。因此
相当于:
并且
ar
包含 3 个元素。6.7.9 Initialization/20 states how such struct elements are initialized:
(emphasis mine)
So it's valid. And thus
is equivalent to:
and
ar
contains 3 elements.这是可能的,原因很简单,标准允许这样做。
那么为什么标准允许呢?嗯,我不知道这背后是否有什么道理。最可能的原因是这仅仅是因为向后兼容性。 C语言充满了这样的东西。
然而,它被认为是不好的风格。所以要避免它。如果您在启用警告的情况下进行编译(应该),您会收到此警告:
与许多其他语言相比,C 背后的哲学非常不同。有人可能会说,即使省略大括号是一种不好的风格,也没有真正的理由禁止省略它们。例如,它不会引起任何歧义。
It's possible for the very simple reason that the standard allows it.
So why does the standard allow it? Well, I don't know if there's any rationale behind this. The most likely reason is that it's simply because of backwards compatibility. The C language is literary full of such things.
However, it is considered bad style. So avoid it. And if you compile with warnings enabled, which you shall do, you get this warning:
And the philosophy behind C is very different compared to many other languages. One could argue that even if it's bad style to omit the braces, there is not really a reason to forbid omitting them. For instance, it does not cause any ambiguity.