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.
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.
A trailing comma, also known as a dangling or terminal comma, is a comma symbol that is typed after the last item of a list of elements. Since the introduction of the JavaScript language, trailing commas have been legal in array literals. Later, object literals joined arrays.
Trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to JavaScript code. If you want to add a new property, you can add a new line without modifying the previously last line if that line already uses a trailing comma.
In Python, a tuple is actually created by the comma symbol, not by the parentheses. Unfortunately, one can actually create a tuple by misplacing a trailing comma, which can lead to potential weird bugs in your code. You should always use parentheses explicitly for creating a tuple.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With