关于枚举成员赋值

yff12321 2015-09-11 10:31:55
例如枚举类型定义如下
{
a=0,
b,
c,
d,
e = 0x7FFFFFFF
}ff;
那么我想问,默认的b、c、d的值是多少?如果不给a赋值,只给e赋值,他们的值又为多少呢?
...全文
417 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
mymtom 2015-09-11
  • 打赏
  • 举报
回复
Semantics The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted./52/ An enumerator with = defines its enumeration constant as the value of the constant expression. If the first enumerator has no = , the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant. (A combination of both forms of enumerators may produce enumeration constants with values that duplicate other values in the same enumeration.) The enumerators of an enumeration are also known as its members. Each enumerated type shall be compatible with an integer type; the choice of type is implementation-defined.
zamely 2015-09-11
  • 打赏
  • 举报
回复
没有显式赋值的都是前面的加1,如果都没有赋值,从0开始。
自信男孩 2015-09-11
  • 打赏
  • 举报
回复
默认后面的是按照第一个的值依次加1的
heroesjun 2015-09-11
  • 打赏
  • 举报
回复
两种情况下输出结果都是一样的,a=0, b=1, 依次加一,因为如果不设定值,第一个枚举值默认为0。
#include <iostream>

using namespace std;

enum ff{
    a = 0,
    b,
    c,
    d,
    e = 0x7FFFFFFF
};


enum ff2{
    a2,
    b2,
    c2,
    d2,
    e2 = 0x7FFFFFFF
};


int main()
{
    ff t = a;
    cout << t <<endl;
    t = b;
    cout << t <<endl;
    t = c;
    cout << t <<endl;


    ff2 t2 = a2;
    cout << t2 <<endl;
    t2 = b2;
    cout << t2 <<endl;
    t2 = c2;
    cout << t2 <<endl;

    return 0;
}
苏叔叔 2015-09-11
  • 打赏
  • 举报
回复
你得亲自试下……
paschen 2015-09-11
  • 打赏
  • 举报
回复
lm_whales 2015-09-11
  • 打赏
  • 举报
回复
未初始化的枚举值,顺次增加 1, 第一个枚举值,没有初始化的,初始化为 0 已经初始化的,以初始化为准 枚举值,是常量,不能赋值,只能初始化 枚举变量,才可以赋值
  • 打赏
  • 举报
回复
依次加1,第一个值默认是0,赋值了什么就变什么

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧