C枚举中的最后一个逗号是否需要? [英] Is the last comma in C enum required?

查看:49
本文介绍了C枚举中的最后一个逗号是否需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C 枚举声明中是否需要最后一个逗号?

Is the last comma required in a C enum declaration?

VAL3 后面的逗号是必需的吗?

i.e. is the comma after VAL3 required?

enum { Val1, Val2, Val3, } someEnum;

将其留在/离开是否有任何副作用

Are there any side-effects of leaving it in/out

谢谢

推荐答案

这不是必需的.C99 的 6.7.2.2 部分列出的语法为:

It's not required. Section 6.7.2.2 of C99 lists the syntax as:

enum-specifier:
    enum identifieropt { enumerator-list }
    enum identifieropt { enumerator-list , }
    enum identifier
enumerator-list:
    enumerator
    enumerator-list , enumerator
enumerator:
    enumeration-constant
    enumeration-constant = constant-expression

注意 enum-specifier 的前两种形式,一种带有尾随逗号,另一种没有.

Notice the first two forms of enum-specifier, one with the trailing comma and one without.

我已经看到使用它的一个优点是:

One advantage I've seen to using it is in things like:

enum {
    Val1,
    Val2,
    Val3,
} someEnum;

如果您想添加(例如)Val4Val5,您只需复制并粘贴 Val3 行而无需担心调整逗号.

where, if you want to add in (for example) Val4 and Val5, you just copy and paste the Val3 line without having to worry about adjusting commas.

它还可以简化自动化代码生成器,这样它们就不必对最终值进行特殊处理.他们可以只输出每个值后跟一个逗号.

It can also be to simplify automated code generators so that they don't have to have special handling for the final value. They can just output every value followed by a comma.

这可以比作常见的 SQL:

This can be likened to the oft-seen SQL:

select fld1, fld2 from tbl where 1=1 and fld1 > 8

在那种情况下,where 1=1 只是存在这样你就不必在你的第一个子句和一个 and 之前放一个 where 在每个后续代码之前.您可以依赖 where 已经存在的事实,只需将 用于您添加的所有内容.

In that case, the where 1=1 is there only so that you don't have to put a where before your first clause and an and before each subsequent one. You can just rely on the fact that the where is already there and just use and for all the ones you add.

有些人可能认为这是一种懒惰的味道,他们是对的,但这不一定是件坏事:-)

Some people may think this reeks of laziness and they're right, but that's not necessarily a bad thing :-)

任何体面的 DBMS 查询优化器都应该能够在进入数据库表之前去掉这样的常量子句.

Any decent DBMS query optimiser should be able to strip out constant clause like that before going to the database tables.

这篇关于C枚举中的最后一个逗号是否需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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