Reputation: 111
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;
}
Upvotes: 7
Views: 9668
Reputation: 1867
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.
Upvotes: 0
Reputation: 8975
You declare, but do not initialize day1
and day2
. As a POD type without default construction, the variables are in an undefined state.
Upvotes: 0
Reputation: 21763
Like any variable, if it is uninitialized the value is undefined. The enum variable is not guaranteed to hold a valid value.
Upvotes: 1
Reputation: 5714
To see some values you need to initialize it first -
DAY day1 = SAT,day2 = SUN;
Upvotes: 0
Reputation: 254431
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.
Upvotes: 15
Reputation: 272467
Because those variables are uninitialised; their values are indeterminate. Therefore, you're seeing the result of undefined behaviour.
Upvotes: 8