Uninitialized enum variable

I declare a new DAY type using an enumeration, and then declare two variables from it day1 and day2, then I should have seen values ​​from 0 to 6 when I used them uninitialized, since the values ​​were between 0 and 6 in the list of enumerations, but I I get these values ​​instead of -858993460.

Can you explain to me why I get these values ​​instead of 0-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; } 
+4
source share
6 answers

Enumeration is not limited to accept only declared values.

It has a base type (a numeric type, at least large enough to represent all values), and with suitable dodgy casting, any value represented by this type can be provided.

In addition, using an uninitialized variable gives undefined behavior, so basically anything can happen.

+11
source

Because these variables are not initialized; their meanings are undefined . Thus, you see the result of undefined behavior.

+5
source

Like any variable, if it is not initialized, the value is undefined. An enumeration variable is not guaranteed to have a valid value.

+1
source

To see some of the values ​​needed to initialize it, first -

 DAY day1 = SAT,day2 = SUN; 
0
source

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

0
source

We can discuss the following code:

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

Uninitialized local variables of type POD may have an invalid value.

0
source

Source: https://habr.com/ru/post/1491875/


All Articles