C++的哪一部分标准允许在括号中声明变量?

发布于 2025-02-08 02:07:58 字数 121 浏览 1 评论 0原文

考虑以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苏别ゝ 2025-02-15 02:07:58

[dcl.manting]在标准中说:

在声明中>与声明t d1

括号不会更改嵌入式声明器-ID 的类型,但它们可以改变复杂声明器的结合。

更简单地说,您可以在C ++语法中围绕被认为是“宣告者”的任何内容。 (松散地说,声明器是声明的一部分,没有初始指定符和包含一个名称的类型。)

在您的示例中,标识符s是声明器,因此您可以放置​​括号周围及其含义不会改变。

正如第二个引用的句子暗示,这样做的原因是,当事情变得更加复杂时,可能是必要的。一个例子:

int * a [10];     // a is an array of ten pointers to int.
int ( * b ) [10]; // b is a pointer to an array of ten ints.

[dcl.meaning] in the Standard says:

In a declaration T D where D has the form ( D1 ) the type of the contained declarator-id is the same as that of the contained declarator-id in the declaration T D1.

Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.

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:

int * a [10];     // a is an array of ten pointers to int.
int ( * b ) [10]; // b is a pointer to an array of ten ints.
再见回来 2025-02-15 02:07:58

只是为了增加其他答案;在语法摘要中,宣言者(C ++ 14 [dcl.decl]/4)您可以找到:(

ptr-declarator:
    noptr-declarator

noptr-declarator:
    ( ptr-declarator )

我省略了语法的其他细节)。您可以从中可以看到,任何声明者都可能被括起来,并且它仍然与同一语法规则相匹配。

Just to add to the other answers; in the grammar summary for declarators (C++14 [dcl.decl]/4) you can find:

ptr-declarator:
    noptr-declarator

noptr-declarator:
    ( ptr-declarator )

(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文