简体   繁体   中英

uninitialized enum variable value

I declare new type DAY by using enum and then declare two variable from it day1 and day2, then I was supposed to see values between 0 to 6 when I used them uninitialized since the values were between 0 to 6 in enumlist , but I receive these values instead -858993460.

can you explain me why I receive these values instead of 0 to 6?

#include <iostream>

using namespace std;

int main()
{
    enum DAY{SAT,SUN,MON,TUE,WED,THU,FRI};
    DAY day1,day2;

    cout<<int(day1)<<endl<<day1<<endl;
    cout<<int(day2)<<endl<<day2<<endl;

    system("pause");
    return 0;
}

An enumeration is not constrained to take only the declared values.

It has an underlying type (a numeric type at least large enough to represent all the values), and can, with suitable dodgy casting, be given any value representable by that type.

Additionally, using an uninitialised variable gives undefined behaviour, so in principle anything can happen.

Because those variables are uninitialised; their values are indeterminate . Therefore, you're seeing the result of undefined behaviour .

Like any variable, if it is uninitialized the value is undefined. The enum variable is not guaranteed to hold a valid value.

要查看某些值,您需要先对其进行初始化 -

DAY day1 = SAT,day2 = SUN;

You declare, but do not initialize day1 and day2 . As a POD type without default construction, the variables are in an undefined state.

We can discuss by the code below:

#include <iostream>
using namespace std;
int main()
{
  int i1, i2;
  cout << i1 << endl << i2 << endl;
}

Uninitialized local variables of POD type could have invalid value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM