枚举值定义中的逗号?

时间:2014-02-18 16:13:50

标签: c enums clang

我有以下标志枚举定义(使用Cocoa宏):

typedef NS_OPTIONS(uint64_t, ItemDataType) {

...

    A = (1 << 16),
    B = (1 << 17),
    C = (1 << 18),
...

    G = (1 << 31),

    TEST = (A | B | C, G)
};

TEST应该是(A | B | C | G),但我们输了一个拼写错误并输入了(A | B | C, G)。这种符号的含义是什么? TEST的实际价值是多少?这不是编译器错误吗?

1 个答案:

答案 0 :(得分:4)

,comma operator,它是有效的代码,它将评估左操作数,然后丢弃该值并评估右操作数,这将是结果。

来自C99标准草案部分6.5.17 逗号运算符 2

  

逗号运算符的左操作数被计算为void表达式;有一个   评估后的序列点。然后评估右操作数;结果有它   类型和价值。 97)

另外值得注意的是逗号运算符具有lowest operator precedence

clang如果您使用-Weverything标志,则提供以下警告:

warning: expression is not an integer constant expression; folding it to a constant is a GNU extension [-Wgnu-folding-constant]
TEST = (A | B | C , G)
       ^~~~~~~~~~~~~~~

这是正确的,值必须是一个常量表达式,因为常量表达式不能包含逗号运算符。

在这种情况下,

gcc会给我一个错误,但如果我使用-Wall标志,则会发出警告:

warning: left-hand operand of comma expression has no effect [-Wunused-value]
 TEST = (A | B | C , G)
                   ^
error: enumerator value for 'TEST' is not an integer constant