在查看 C 的 BNF 语法时,我认为声明的产生式规则看起来很奇怪(根据 https://cs.wmich.edu/~gupta/teaching/cs4850/sumII06/The%20syntax%20of%20C%20in%20Backus-Naur%20form.htm ):
<declaration> ::= {<declaration-specifier>}+ {<init-declarator>}* ;
为什么要使用
*
init-declarator
的量词(表示出现零次或多次) ?这允许诸如 int;
之类的语句或 void;
语法上有效,即使它们在语义上无效。难道他们不能用 +
量词(出现一次或多次)而不是 *
在生产规则中?我尝试编译一个简单的程序来查看编译器输出的内容,它所做的只是发出警告。
输入:
int main(void) {
int;
}
输出:
test.c: In function ‘main’:
test.c:2:5: warning: useless type name in empty declaration
int;
^~~
最佳答案
declaration-specifier
包括 type-specifier
,其中包括 enum-specifier
.一个像
enum stuff {x, y};
是有效的
declaration
没有 init-declarator
.构造如
int;
被 constraints beyond the grammar 排除:A declaration other than a static_assert declaration shall declare at least a declarator (other than the parameters of a function or the members of a structure or union), a tag, or the members of an enumeration.
我猜你的编译器只发出警告背后有向后兼容的原因。
关于c - 为什么 C 的 BNF 语法允许使用空的 init-declarators 序列进行声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61026348/