[英]why is `int test {}` a function definition in C language BNF
I'm interested in the famous The syntax of C in Backus-Naur Form and studied for a while, what confuse me is that some syntax looks wrong to me but is considered right according to the BNF. 我对Backus-Naur Form中着名的C语法感兴趣并研究了一段时间,让我感到困惑的是,某些语法对我来说看起来不对,但根据BNF认为是正确的。
For example, int test {}
, what's this? 例如, int test {}
,这是什么? I think this is a ill syntax in C, but the truth is the BNF considered this a function definition: 我认为这在C语言中是一种错误的语法,但事实是BNF认为这是一个函数定义:
int -> type_const -> type_spec -> decl_specs
test-> id -> direct_declarator -> declarator
'{' '}' -> compound_stat
decl_specs declarator compound_stat -> function_definition
I tried this with bison, it considered the input int test {}
is a right form, but I tried this on a C compiler, it will not compile. 我用bison尝试了这个,它认为输入int test {}
是一个正确的形式,但我在C编译器上尝试过这个,它不会编译。
So got questions: 所以有问题:
int test {}
a right syntax or not? int test {}
一个正确的语法与否? The grammar is necessary but not sufficient to describe a valid C program. 语法是必要的,但不足以描述有效的C程序。 For that you need constraints from the standard too. 为此,您也需要标准的约束 。 A simpler example of this would be 0++
, which follows the syntax of a C expression, but certainly isn't a valid program fragment... 一个更简单的例子是0++
,它遵循C表达式的语法,但肯定不是一个有效的程序片段......
The footnote 162 explains that the intent of the constraint is that a typedef
cannot be used , ie that 脚注162解释了约束的意图是不能使用 typedef
,即
typedef int F(void);
F f { /* ... */ }
will not be valid, even though such a typedef
could be used for a function declaration , ie 即使这样的typedef
可用于函数声明 ,即无效
F f;
would declare the function 会声明这个功能
int f(void);
But mere existence of this constraint also proves that the BNF grammar in itself is not sufficient in this case. 但仅仅存在这种约束也证明了BNF语法本身在这种情况下是不够的。 Hence you are correct in that the grammar would consider such a fragment a function definition. 因此,你是正确的,因为语法会将这样的片段视为函数定义。
The BNF form is a precise way to describe the syntax of a language, ie what to do precisely to get the parse tree starting from raw input. BNF表单是描述语言语法的精确方式,即准确地从原始输入开始解析树的操作。
For each language you can define infinite many grammars that describe that language. 对于每种语言,您可以定义无限多个描述该语言的语法。 The properties of these grammars that describe the same language can differ a lot. 描述相同语言的这些语法的属性可能有很大不同。
If you study the grammar of the C language, take care as it is not context free but context sensitive, which means, the decision of choosing a rule or other depends on what there is around that point in input. 如果您研究C语言的语法,请注意,因为它不是上下文而是上下文敏感,这意味着,选择规则或其他规则的决定取决于输入中该点的内容。
Read about the lexer hack
to see how to correctly interpret the Backus Naur form of the C grammar. 阅读有关lexer hack
,了解如何正确解释Backus Naur形式的C语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.