尾随逗号和C ++ [英] Trailing commas and C++

查看:107
本文介绍了尾随逗号和C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过的地方,C ++标准不允许像枚举an_enum {A,B,C,}; ,而C的更高版本(我想从90年代中期)都允许这样的声明(用逗号结尾)。如果C ++应该有使用C向后兼容性,怎么来的这个功能是被禁止的?任何特别的原因?

I've 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(这是C ++ 98相当次要更新)立足于C89的C兼容性(也被称为C90,这取决于你'重新ANSI或ISO)。 C89不允许尾随逗号。 C99确实允许它。 C ++ 11确实允许它(7.2 / 1有一个枚举声明语法)。

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).

在事实上C ++是不完全向后兼容,即使C89,虽然这是,如果它当时在C89,你所期望的C ++允许它的那种东西。

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
};

但是,(一)这是疯话,和(b)它并不要在开始添加新价值(无可否认罕见)的情况下帮助。

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.

这篇关于尾随逗号和C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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