为什么"int test {}"是C语言BNF中的函数定义 [英] why is `int test {}` a function definition in C language BNF
语法对于描述有效的C程序是必需的,但又不是足够.为此,您还需要标准中的约束.一个更简单的例子是0++
,它遵循C表达式的语法,但肯定不是有效的程序片段...
- 在函数定义中声明的标识符(即函数的名称)应具有函数类型,由函数定义的声明符部分指定. 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.
For example,
int test {}
, what's this? I think this is a ill syntax in C, but the truth is the BNF considered this a function definition: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.So got questions:
int test {}
a right syntax or not?- If it is a right syntax, what is that mean and why compiler do not recognized it?
- If it is an ill syntax, can I say the BNF is not rigorous? And does that mean modern C compiler does not stick with this BNF?
解决方案The grammar is necessary but not sufficient to describe a valid C program. 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...
- The identifier declared in a function definition (which is the name of the function) shall have a function type, as specified by the declarator portion of the function definition. [162]
The footnote 162 explains that the intent of the constraint is that a
typedef
cannot be used, i.e. thattypedef int F(void); F f { /* ... */ }
will not be valid, even though such a
typedef
could be used for a function declaration, i.e.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. Hence you are correct in that the grammar would consider such a fragment a function definition.
这篇关于为什么"int test {}"是C语言BNF中的函数定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!