简体   繁体   English

enum变量的默认值是多少?

[英]what is the default value of enum variable?

I have a question about enum variable in c++: 我对c ++中的枚举变量有疑问:

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

void main() {
   DAYS days;
}

then what is the default value of days? 然后天的默认值是多少?

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. 在初始化之前, x没有值。

then what is the default value of days?` 然后天的默认值是什么?`

Like for any automatic object, the value of the days object is indeterrminate. 与任何自动对象一样, days对象的值是不确定的。

Now if you declared your object with the static specifier: 现在,如果使用static说明符声明对象:

static DAYS days;

Then like for any static object of an arithmetic type, the initial value would be 0 . 然后,对于任何算术类型的静态对象,初始值将为0

Enumerations behave pretty much like integers, ie they don't have a well-defined default value. 枚举的行为与整数非常相似,即它们没有明确定义的默认值。 You cannot read the variable's value before initializing it without invoking undefined behavior. 在初始化变量之前,无法读取变量的值而不调用未定义的行为。

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). 但要小心 - 它将是0(以及所有其他静态变量)。 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. 它将打印0,但您的枚举范围为1..3。 So be aware of it. 所以要注意它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM