本文介绍了为什么"int test {}"是C语言BNF中的函数定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对著名的 Backus-Naur形式的C语法,并研究了一段时间,令我感到困惑的是,某些语法在我看来错了,但根据BNF却被认为是正确的.

例如int test {},这是什么?我认为这在C语言中是一种错误的语法,但事实是BNF认为这是一个函数定义:

int -> type_const -> type_spec -> decl_specs
test-> id -> direct_declarator -> declarator
'{' '}' -> compound_stat
decl_specs declarator compound_stat -> function_definition

我用bison尝试过,它认为输入int test {}是正确的形式,但是我在C编译器上尝试过,它将无法编译.

所以有问题:

  1. int test {}语法是否正确?
  2. 如果语法正确,那是什么意思,为什么编译器无法识别它?
  3. 如果语法错误,我可以说BNF不严格吗?这是否意味着现代C编译器不坚持使用此BNF?
解决方案

语法对于描述有效的C程序是必需的,但又不是足够.为此,您还需要标准中的约束.一个更简单的例子是0++,它遵循C表达式的语法,但肯定不是有效的程序片段...

C11 6.9.1p2 :

脚注162解释了约束的意图 是不能使用typedef ,即

typedef int F(void);
F f { /* ... */ }

即使这样的typedef可以用于函数声明(即

),

也将无效.

F f;

将声明函数

int f(void);

但是仅存在此约束也证明,在这种情况下,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.

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:

  1. int test {} a right syntax or not?
  2. If it is a right syntax, what is that mean and why compiler do not recognized it?
  3. 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...

C11 6.9.1p2:

The footnote 162 explains that the intent of the constraint is that a typedef cannot be used, i.e. that

typedef 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中的函数定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:53
查看更多