Search code examples
c++initializationclion

Why the defaultly initialized value of an integer is 4200187 in C++?


from 2.2.1 variable definitions of "C++ primer" , "variables defined outside any function body are initialized to zero". However, like the following code, I define an integer i and print it out. why the result is 4200187? (I use Clion)

Update: thank you for your anwsers! now I know that i is defined inside the main function, and then i is not defined. But why an undefined integer has the value os 4200187?

#include <iostream>

int main() {
    int i;
    std::cout << i << std::endl;
}

the result:

4200187

Process finished with exit code 0

Solution

  • I think the document you're referring to is talking about this kind of variables:

    #include <iostream>
    
    int i;
    
    int main() {
        std::cout << i << std::endl;
    }
    

    Variables declared this way are guaranteed to be initialized at 0 whereas non-static primitive variables created inside of a function are uninitialized.

    According to the specification reading from an uninitialized variable causes undefined behavior and your compiler should print out a warning if you try.

    Hence, the value you got isn't an "expected value" from C++, just a value your compiler felt like printing this one time. As 463035818_is_not_a_number said, undefined behavior is just that, undefined. Most compiler will try to be nice and preserve as much of the functionality of the program as possible (that's probably why it still printed something to the console) but I'd recommend against trusting it with that, anything can happen.