gpt4 book ai didi

c - 隐式函数声明有时在 C 中有效?

转载 作者:行者123 更新时间:2023-12-01 12:50:20 24 4
gpt4 key购买 nike

有人可以向我解释为什么以下编译:

int main()
{
int a = mymethod(0);
}
int mymethod(int b)
{
return b;
}

但这不是:

int main()
{
mymethod(0);
}
void mymethod(int b)
{
return;
}

我认为 C/C++ 中需要前向声明,但这是一个反例。隐式声明在 C 中如何工作?

最佳答案

我假设当你说它在第二个代码示例中不起作用时,你的意思是你遇到了编译时错误。

原因是当有一个隐式函数声明时,假定它接受固定数量的参数,并返回int。但是,mymethod() 首先被隐式声明,然后声明返回 void。这是一个错误,因为新声明与以前的(隐式)声明不匹配。

C90 (ANSI C89) 允许隐式函数声明。来自 C89,第 3.3.2.2 节:

If the expression that precedes the parenthesized argument list in a function call consists solely of an identifier, and if no declaration is visible for this identifier, the identifier is implicitly declared exactly as if, in the innermost block containing the function call, the declaration

extern int  identifier();
appeared.

但是,此津贴已从 C99 中删除(因此在 C11 中也是不允许的)。 C++ 从不允许隐式函数声明。

关于c - 隐式函数声明有时在 C 中有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17937909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com