7

I have a question about enum variable in c++:

type enmu {
   DAY1 = 1,
   DAY2,
   DAY3,
   DAY4
} DAYS;

void main() {
   DAYS days;
}

then what is the default value of days?

4 Answers4

8

It's uninitialized and undefined behavior to read the value.

Just like saying

int x;

x doesn't have a value until you initialize it.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

then what is the default value of days?`

Like for any automatic object, the value of the days object is indeterrminate.

Now if you declared your object with the static specifier:

static DAYS days;

Then like for any static object of an arithmetic type, the initial value would be 0.

ouah
  • 142,963
  • 15
  • 272
  • 331
1

Enumerations behave pretty much like integers, i.e. they don't have a well-defined default value. You cannot read the variable's value before initializing it without invoking undefined behavior.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

BTW, adding to the words, said before: you really do may have default value for a static enum variable. But be carefull -- it will be 0 (as well as all other static variables). Consider following code:

#include <iostream>

enum _t_test {
                test_1 = 1,
                test_2 = 2,
                test_3 = 3,
             };

static enum _t_test t;

int main()
{
    using namespace std;
    cout << "Value of t is: " << t;
    return 0;

}

It will print 0, but your enums are in range from 1..3. So be aware of it.

Xentatt
  • 1,264
  • 22
  • 35