未初始化的枚举变量值 [英] uninitialized enum variable value

查看:202
本文介绍了未初始化的枚举变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过使用枚举来声明新的DAY类型,然后从它day1和day2声明两个变量,然后当我使用它们未初始化时,我应该看到0到6之间的值,因为值在枚举列表中是0到6之间,但是我收到这些值,而不是-858993460。



你能解释一下为什么我收到这些值而不是0到6?

 #include< iostream> 

使用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;
}


解决方案

枚举不限于只需要声明的值。



它有一个底层类型(一个数字类型至少足以表示所有的值),可以可以用适当的诡计来赋予任何值。



此外,使用未初始化的变量给出了未定义的行为,所以原则上可以发生任何事情。 >

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;
    }

解决方案

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.

这篇关于未初始化的枚举变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆