在gcc中似乎允许本地函数声明,我在这里找到了一个相关的讨论:Is there any use for local function declarations?
然而,我的问题是:它是否符合ISO C标准?如果是,如何解释以下现象,从而使人感到困惑:
int main(void) {
int f(void);
f();
}
void g(void) {
/* g has no idea about f. It seems that the decl is limited within its
* scope */
f();
}
int f(void) {}
while
int main(void) {
int f(void);
f();
}
void f(void); /* error because disagreement with the local declaration (local
declaration goes beyound its scope?) */
void f(void) { /* definition here */ }
根据C99标准:函数名属于同一命名类别。因此,我们需要讨论作用域机制来解释这个问题。但是如何呢?
实际上,我正在进行编译器课程项目,需要我们实现简化版的C编译器。我试图处理这种情况,但是感到困惑。
编辑:我知道C是面向过程的,并且要求函数名唯一。但是这种局部声明风格使情况变得清晰,很难理解其原则/规则。
main
中的函数声明和它外部的函数声明不共享作用域。然而,你有两个不同类型的同名声明。你只能有一个f
函数定义。 - ajaymain
内部和外部调用f
,因为只能有一个f
的定义,并且它不能匹配两个声明,因为它们具有不同的返回类型。 - ajay