C++ 的语法翻译单位
长期以来,我的理解是,C++ 翻译单元,在预处理器运行后,是一系列声明(让我提醒一下,任何定义也是声明)。
很多人对这种说法提出异议,但没有人给出反例。但我自己发现这个例子让我很困扰:
int x; //declaration
; // ??? EMPTY DECLARATION?
int main() //dec
{ //la
} //ration
这个可以用 MSVC 和在线 comeau 编译得很好。我知道该标准定义了空声明,但我从未听说过空声明。所以,我看到三个选项:
- 我的理解是正确的,标准定义了一个空声明
- 我的理解是正确的,但标准没有定义空声明,并且上述翻译格式不正确
- 我的理解不正确,即 C++ TU 不是一系列声明
请帮助我消除我的疑虑。谢谢
My understanding, for a long time now, was that a C++ translation unit, after the preprocessor has run, is a sequence of declarations (let me remind that any definition is also a declaration).
Many people have argued with this statement but no one has ever given a counterexample. But I myself found this example which troubles me:
int x; //declaration
; // ??? EMPTY DECLARATION?
int main() //dec
{ //la
} //ration
This compiles fine with MSVC and online comeau. I know the standard defines an empty statement but I never heard of an empty declaration. So, I see three options:
- My understanding is correct and the standard defines an empty declaration
- My understanding is correct but the standard doesn't define empty declarations and the above translation is ill-formed
- My understanding is incorrect, i.e. a C++ TU is not a sequence of declarations
Please help me dissolve my doubts. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
C++0x(当前草案)中允许在文件范围(以及命名空间范围和其他允许声明的地方)使用空声明,并且它只是一个分号。它是一个独立的语法实体。
在 C++03 中,仅需要声明的地方不允许使用单独的分号。尽管看起来简单声明可能能够减少到只有一个分号,但明确的规则不允许这样做。
7 [dcl.dcl] / 3
在简单声明中,可选的init-declarator-list仅在声明类(第9条)或枚举(7.2)时可以省略,即当decl -specifier-seq 包含一个类说明符、一个带有类键的详细类型说明符 (9.1) ,或枚举说明符。
简而言之,这意味着只有在不省略 decl-specifier-seq 时才能省略 init-declarator-list 。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您的理解是正确的,标准(或至少 Stroustrup)确实定义了一个空声明。编辑:看来这个答案是错误的(据我所知,标准上有一个语义规则 - 但书上没有 - 它禁止
decl-specified-seq 和
init-declarator-list
同时为空)。请参阅查尔斯·贝利的回答。n 《C++ 编程语言》,附录 A,A.4 节:
opt
表示产生式是可选的。在此规则中,意味着空的翻译单元是有效的。A.7 节:
所以
declaration-seq
是至少一个declaration
的序列。除其他外,声明
可以是块声明
,它又生成简单声明
。由于 decl-specified-seq 和 init-declarator-list 非文字都是可选的,因此;
是有效的声明。Your understanding is correct and the standard (or at least Stroustrup) does define an empty declaration.EDIT: It seems this answer is wrong (there's a semantic rule on the standard - but not on the book, as far as I can tell - that prohibits both
decl-specified-seq
andinit-declarator-list
of being empty at the same time). See Charles Bailey's answer.n "The C++ Programming Language", appendix A, section A.4:
opt
means the production is optional. In this rule, it means an empty translation unit is valid.Section A.7:
So
declaration-seq
is a sequence of at least onedeclaration
. Adeclaration
can, amongst other things, be ablock-declaration
, which in turn producessimple-declaration
. As both thedecl-specified-seq
andinit-declarator-list
non-literals are optional,;
is a valid declaration.