What is the default value of the enum variable?

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 for days?

+7
source share
4 answers

This is uninitialized behavior and undefined to read values.

Same as say

 int x; 

x does not matter until you initialize it.

+8
source

then what is the default value for days? `

As with any automatic object, the value of the days object is indeterrminate.

Now, if you declared your object a static specifier:

 static DAYS days; 

Then, as for any static object of arithmetic type, the initial value will be 0 .

+2
source

Enumerations behave as integers, i.e. do not have a clearly defined default. You cannot read the value of a variable before initializing it without invoking undefined behavior.

0
source

By the way, adding to the words said earlier: you really can have a default value for the static enum variable. But be careful - this will be 0 (like all other static variables). Consider the 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 listings are in the range of 1..3. Therefore, keep this in mind.

0
source

All Articles