What happens to uninitialized variables? C++

前端 未结 3 1445
北海茫月
北海茫月 2020-11-29 12:58
int main()
{    
    int a;
    cout << a;
    return 0;
}

I am wondering why the value 0 is being output. I thought if a variable is uniniti

相关标签:
3条回答
  • 2020-11-29 13:17

    The default behavior of an uninitialized function scope (i.e., local) integer in C++ is for it to be indeterminate, which is fine; however if that value is used before it is defined it introduces undefined behavior, and anything could happen - demons could fly out of your nose.

    This page on cppreference provides examples of default integer behavior.

    On the other hand, all non-local, thread-local variables, not just integers, are zero initialized. But this case wasn't included in your original example.

    (Side note: It is generally considered good practice to simply initialize variables anyway and avoid potential hazards altogether... Especially in the form of global variables. )

    There are exceptions to best practice using global variables in rare special cases, such as some embedded systems; which initialize values based off of sensor readings on startup, or during their initial loop iteration... And need to retain a value after the scope of their loop ends.

    0 讨论(0)
  • 2020-11-29 13:25

    Well the reason being, a variable gets garbage value( a value unknown/senseless to program) is when someone runs a program, it gets loaded in some part of RAM. Now it all depends what values were previously set to certain location, may be some other program was there previously. It just happen the your program has loaded into a that location where it happens to be 0 value in RAM and that's what you are getting in return.

    It quite possible that if restart your system and try running the same program then you might get garbage value.

    Above statements are valid for variables which doesn't get initialized by the compiler.

    0 讨论(0)
  • 2020-11-29 13:33

    I think you are not convinced with the answers/comments given, may be you can try the below code:

    #include <iostream>
    using namespace std;
    
    int main(){
    
     int a,b,c,d,e,f,g,h,i,j;
    
     cout<<a<<endl;
     cout<<b<<endl;
     cout<<c<<endl;
     cout<<d<<endl;
     cout<<e<<endl;
     cout<<f<<endl;
     cout<<g<<endl;
     cout<<h<<endl;
     cout<<i<<endl;
     cout<<j<<endl;
    
     return 0;
    }
    
    0 讨论(0)
提交回复
热议问题