Can a variable be redeclared as auto that deduced to the same type? [duplicate]

六眼飞鱼酱① 提交于 2019-12-04 17:24:37

问题


Is the following allowed by the standard?

#include <iostream>

extern int a;
auto a = 3;

int main(int, char**)
{
    std::cout << a << std::endl;
    return 0;
}

clang accepts the code. g++ complains for conflicting declaration.


回答1:


Its not much clear to me from the standard, but then, there is this written

section 7.1.6.4 auto specifier
A program that uses auto in a context not explicitly allowed in this section is ill-formed.

Better read the mentioned section of the standard for all the allowed contexts.

Considering this, I believe g++ is correct and clang is wrong. But I could be wrong, there could be some separate section in standard which might be implying this context, but I could not find it.




回答2:


Edit answer: As mention in the comments. The problem in this case is that writting

external int a;
auto a = 3;

is the same as writting

external int a;
int a = 3;

that means you have a new definition of a and that causes an error.

First answer: For my understanding this breaks parts of the One definition rule. Specifically, I mean the following rule (in reference to MISRA C++ 2008) that says that an identifier with external linkage should always have only one definition. In your example you have a definition in the current file(auto a = 3;) and with external you also refer to a definition in another file.



来源:https://stackoverflow.com/questions/37407547/can-a-variable-be-redeclared-as-auto-that-deduced-to-the-same-type

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