Why is initialization of a new variable by itself valid? [duplicate]

元气小坏坏 提交于 2019-11-26 10:00:02

问题


Consider some code:

#include <iostream>

int main()
{
    using std::cout;
    int a=3;
    cout << \"a=\"<<a<<\"\\n\";

    {
        int a=a;
        cout << \"new a = \" << a << \"\\n\";
        a=5;
        cout << \"a = \" << a << \"\\n\";
    }
    cout << \"old a = \" << a << \"\\n\";
}

I\'d expect it to print

a=3
new a = 3
changed a = 5
old a = 3

But what I get actually appears to say new a = 0 in the second line. I thought that it would work like initialization list in a class\' constructor, where one can write like

C::C(int a) : a(a) {}

But for some reason this is different. First, removing the outer code completely doesn\'t result in a compilation error. So I assume that int a=a; is valid. Turning on all the compiler warnings leads to this:

test.cpp: In function ‘int main()’:
test.cpp:10:15: warning: ‘a’ is used uninitialized in this function
         int a=a;

So my question now: why is this syntax valid at all? Why doesn\'t the compiler say something like \"undefined variable a\"?


回答1:


It's syntactically valid, since the variable's point of declaration comes before its initialiser, and the name is available anywhere after that point. This allows less dodgy initialisations like

void *p = &p;

which legitimately uses the name (but not the value) of the variable being initialised.

It's behaviourally invalid, since using the value of an uninitialised object gives undefined behaviour. That's not an error that requires diagnosis (since, in general, it can be difficult or impossible to analyse the program flow to see whether an object has been initialised), but as you note, many compilers will give a warning for straightforward cases like this.



来源:https://stackoverflow.com/questions/28152298/why-is-initialization-of-a-new-variable-by-itself-valid

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