Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uninitialized enum variable value

Tags:

c++

enums

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;
}
like image 667
Felix Avatar asked Jul 17 '13 12:07

Felix


People also ask

What is the value of an uninitialized enum?

The default value of an uninitialized enumeration, just like other value types, is zero.

What is the default value for enum variable?

The default value of an enumeration type E is the value produced by expression (E)0 , even if zero doesn't have the corresponding enum member.

What is the default value of an uninitialized?

An uninitialized variable has an indeterminate value (except when the variable is declared in static memory, then it has an initial value of 0 if you don't set a value explicitly).

What does an uninitialized variable contain?

In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.


2 Answers

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.

like image 58
Mike Seymour Avatar answered Sep 29 '22 22:09

Mike Seymour


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

like image 21
Oliver Charlesworth Avatar answered Sep 29 '22 22:09

Oliver Charlesworth