7

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;
}
1
  • Uninitialized means uninitialized - it could be anything. Commented Jul 17, 2013 at 12:38

6 Answers 6

15

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.

0
8

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

1

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

0

To see some values you need to initialize it first -

DAY day1 = SAT,day2 = SUN;
0

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

0

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.