C++的哪一部分标准允许在括号中声明变量?
考虑以下代码:
int main() {
int(s);
}
我对其创建有效变量s
的事实感到惊讶。谁能解释这里发生了什么?
Consider the following code:
int main() {
int(s);
}
I am surprised by the fact that it creates valid variable s
. Can anyone explain what's happening here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
[dcl.manting]在标准中说:
更简单地说,您可以在C ++语法中围绕被认为是“宣告者”的任何内容。 (松散地说,声明器是声明的一部分,没有初始指定符和包含一个名称的类型。)
在您的示例中,标识符
s
是声明器,因此您可以放置括号周围及其含义不会改变。正如第二个引用的句子暗示,这样做的原因是,当事情变得更加复杂时,可能是必要的。一个例子:
[dcl.meaning] in the Standard says:
More simply, you can put parentheses around anything considered a "declarator" in the C++ grammar. (Loosely speaking, a declarator is a part of a declaration without the initial specifiers and types which contains one name.)
In your example, the identifier
s
is a declarator, so you're allowed to put parentheses around it and the meaning doesn't change.The reason for this, as the second quoted sentence hints, is that it can be necessary when things get more complicated. One example:
只是为了增加其他答案;在语法摘要中,宣言者(C ++ 14 [dcl.decl]/4)您可以找到:(
我省略了语法的其他细节)。您可以从中可以看到,任何声明者都可能被括起来,并且它仍然与同一语法规则相匹配。
Just to add to the other answers; in the grammar summary for declarators (C++14 [dcl.decl]/4) you can find:
(I have omitted other details of the grammar). You can see from this that any declarator may be parenthesized and it would still match the same grammar rule.