0

Ignoring static and * (for an omitted size) in between the [] brackets, the syntax for an array declarator is (from C99 TC3 (n1256) 6.7.5 p1; C11 (n1570) 6.7.6 p1):

direct-declarator: direct-declarator [ type-qualifier-listopt assignment-expressionopt ] [...]

Thus, a declaration like

int foo[0,1];

is a syntax error, but

int foo[(0,1)];

is allowed (at block scope, as this is a VLA).

There are certain cases where arbitrary expressions aren't allowed because this would cause ambiguity with comma used as a separator. For example, the arguments of a function call must be assignment expressions. I don't see, however, how such an ambiguity could be caused by

direct-declarator: direct-declarator [ type-qualifier-listopt expressionopt ]

Would this define a strict superset of the C language? Are there examples where this grammar is ambiguous?

C89*) required a constant expression in the syntax (which is a conditional expression) so this needed to be changed for C99 to allow VLAs. But I fail to see why it was changed to an assignment expression rather than to an expression. Is there any technical reason?

Gcc (and perhaps other compilers) had VLAs as an extension before they were added to the C standard, a conflict with some other extension could also be an explanation, but I'm not aware of such an extension. Gcc 3.0.4 accepts int a[0,1]; (with -std=gnu89 and -traditional), newer versions (tested with Gcc (Debian) 4.7.2-5) don't, so this looks unlikely to be the cause.

As far as I can see, this question equivalently applies to direct abstract declarators in type names.

*) According to this C89 draft, 3.5.4.

4

1 回答 1

2

允许在数组边界中使用逗号运算符肯定不会产生歧义。毫无疑问,委员会不允许这样做是有原因的,但对于我们这些没有参加讨论的人来说,这只能是猜测。

我推测其中一个动机是避免造成混乱。许多其他语言允许使用逗号分隔的边界列表声明多维数组,习惯于其中一种语言的人可能很容易错误地编写int a[2,7];以获得二维数组。如果允许使用逗号运算符,这将导致声明一个七元素一维数组,并且不会产生错误消息。尝试索引这样的数组也不会产生错误消息,因此编译器不会注意到错误,这可能被认为是不幸的。

但这只是一个疯狂的猜测。

于 2015-03-01T03:12:03.600 回答