What is the purpose of a declaration like int (x); or int (x) = 10;

社会主义新天地 提交于 2019-11-26 17:45:58

问题


If you look at the grammar for *declarator*s in §8/4 you'll notice that a noptr-declarator can be written as (ptr-declarator), that is, it can be written as (declarator-id), which validates declarations like the ones in the title. As matter of fact this code compiles without a problem:

#include <iostream>
struct A{ int i;};
int (x) = 100;
A (a) = {2};
int main()
{
    std::cout << x << '\n';
    std::cout << a.i << '\n';
}

But what is the purpose of allowing these parentheses when a pointer (to an array or to a function) is not involved in the declaration?


回答1:


The fact that this rule is applicable in your case is not deliberate: It's ultimately a result of keeping the grammar simple. There is no incentive to prohibit declarations such as yours, but there are great disincentives to complicate rules, especially if those are intricate as they are.

In short, if you don't want to use this needlessly obfuscated syntax, don't.
C++ rarely forces you to write readable code.

Surprisingly there are scenarios in which parentheses can save the day, though:

std::string foo();

namespace detail
{
    int foo(long); // Another foo

    struct Bar
    {
        friend std::string ::foo(); // Doesn't compile for obvious reasons.

        friend std::string (::foo)(); // Voilà!
    };
}



回答2:


You're asking the wrong question. The correct question is:

What is the purpose of disallowing such a declaration?

The answer is: there is none.

So, given that this syntax is allowed as a side-effect of rules elsewhere, this is what you get.



来源:https://stackoverflow.com/questions/26832321/what-is-the-purpose-of-a-declaration-like-int-x-or-int-x-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!