c - 为什么 C 的 BNF 语法允许使用空的 init-declarators 序列进行声明?

标签 c language-lawyer context-free-grammar

在查看 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/

相关文章:

c++ - 在 C 或 C++ 中是否有等效于 setvbuf() 的方法来处理宽字符?

c++ - 使用 Boost Spirit 的指数运算符表达式语法

context-free-grammar - 常规语法与上下文无关语法

python - 简约 - 规则 'rules' 完全匹配,但它没有消耗所有文本

c++ - GCC 和 -W 转换

c - 使用 C/C++ 解析电子邮件 header 字段

c - 如何设计一个信号安全的 shell 解释器

c - 使用套接字向 C 中的本地 IP 进行 GET 请求

c++ - #error 指令中是否允许使用非拉丁字符?

c++ - 对象生命周期,在什么情况下重用存储?