开发者

Trailing commas and C++

开发者 https://www.devze.com 2023-03-13 21:30 出处:网络
I have read somewhere that the C++ standard does not allow something like enum an_enum { a, b, c, };, while later versions of C 开发者_如何学编程(I think from mid-90s) do allow such declarations with

I have read somewhere that the C++ standard does not allow something like enum an_enum { a, b, c, };, while later versions of C 开发者_如何学编程(I think from mid-90s) do allow such declarations with trailing commas. If C++ is supposed to have backwards compatibility with C, how come this feature is forbidden? Any special reason?

I also read that such trailing commas are actually good, so that just adds to the confusion.


C++03 (which is a fairly minor update of C++98) bases its C compatibility on C89 (also known as C90, depending on whether you're ANSI or ISO). C89 doesn't allow the trailing comma. C99 does allow it. C++11 does allow it (7.2/1 has the grammar for an enum declaration).

In fact C++ isn't entirely backward-compatible even with C89, although this is the kind of thing that if had it been in C89, you'd expect C++ to permit it.

The key advantage to me of the trailing comma is when you write this:

enum Channel {
    RED,
    GREEN,
    BLUE,
};

and then later change it to this:

enum Channel {
    RED,
    GREEN,
    BLUE,
    ALPHA,
};

It's nice that only one line is changed when you diff the versions. To get the same effect when there's no trailing comma allowed, you could write:

enum Channel {
    RED
   ,GREEN
   ,BLUE
};

But (a) that's crazy talk, and (b) it doesn't help in the (admittedly rare) case that you want to add the new value at the beginning.


Looking at the latest draft for C++0x it looks like you can use trailing commas:

enum-specifier:
enum-head { enumerator-list opt}
enum-head { enumerator-list , }

enumerator-list:
enumerator-definition
enumerator-list , enumerator-definition


For one thing, the last C standard was in 1999. The last (complete) C++ standard was 98 (2003 was an update). After that, not all of C99 is going into C++11.


Trailing comma in enum was introduced in C99 as a feature. It does not exist in C90 nor C++ versions that were based on a pre-C99 baseline.

0

精彩评论

暂无评论...
验证码 换一张
取 消