Why is initialization of a new variable by itself

2020-01-26 11:23发布

问题:

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.