Search code examples
c++undefined-behavior

Why is the value of i == 0 in this C++ code?


I am confused about the following code:

#include <iostream>

int i = 1;
int main()
{
    int i = i;
    std::cout << "i: " << i << "\n";
    return 0;
}

Output:

i: 0

I had expected running the above code would print 1. Can someone please explain the reason for this strange behavior?


Solution

  • You are initializing i with itself. The both i's in int i = i; are the inner one not the outer one. This is undefined behavior and you may get 0 or anything may happen.

    This is the right way if you want to assign the outer i to the inner i.

    #include <iostream>
    
    int i = 1;
    int main()
    {
        int i = ::i;
        std::cout << "i: " << i << "\n";
        return 0;
    }
    

    Live Demo


    BTW, You should carefully read all the compiler warnings. If you did you could see the problem yourself:

    warning 'i' is used uninitialized in this function