Does a declaration using “auto” match an extern declaration that uses a concrete type specifier?

前端 未结 3 959
面向向阳花
面向向阳花 2020-11-27 19:11

Consider the following program:

extern int x;
auto x = 42;
int main() { }

Clang 3.5 accepts it (live demo), GCC 4.9 and VS2013 do not (live

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 19:46

    I'd imagine the restriction in [dcl.spec.auto]p11 exists because otherwise, that would allow:

    int f();
    auto f(); // What's the return type here?
    

    The thing is, you can have an undeduced type type has the return type of a function. There are no deduction rules based on previous declarations, which is why such mixing is disallowed for functions, even though the following would be perfectly fine:

    int f();
    auto f() { return 1; }
    

    This problem does not exist for variables:

    extern int v;
    extern auto v; // ill-formed
    

    Any declaration-only variables has to use a non-placeholder type. What this means is that if you use a placeholder type for the definition of v, it can get deduced without any problems and then of course has to match the non-placeholder type used in the first declaration.

    extern int v;
    auto v = 1; // ok, type deduced as 'int', matches first declaration.
    

提交回复
热议问题