gpt4 book ai didi

c++ - C 中的嵌套函数?

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:01 26 4
gpt4 key购买 nike

谁能告诉我我们可以在用户定义的函数中声明一个函数吗?比如

int sum(int x, int y)
{
int fun( float x);
}

我们可以在函数内部定义一个函数吗?据我所知,我们不能在函数内部定义函数。

但我只是这样做了,它的工作正常,代码如下:

{
int main()
{
func1();
return 0;
}
func1()
{
int i = 0;
auto func2()
{
i = 10;
printf("Heloo i am func 2\n");
}
printf("Heloo i am func 1\n");
func2();
}
}

效果很好。

现在有人能告诉我函数内部的函数是如何定义或正常工作的吗?

任何人都可以向我解释为什么代码有效吗?

现在,当我更改几行代码时,出现了以下问题变化如下:

代码:

{
func1()
{
func2();
int i = 0;
auto func2()
{
i = 10;
printf("Heloo i am func 2\n");
}
printf("Heloo i am func 1\n");
}

错误:

error: static declaration of ‘func2’ follows non-static declaration
note: previous implicit declaration of ‘func2’ was here

现在这些错误是什么,为什么会出现?

如果我在 main 函数中调用 func2() ,它会显示如下错误对 func2 的 undefined reference

现在谁能告诉我这里出了什么问题?

最佳答案

C 标准允许在函数内声明函数(如您的第一个代码片段),但不允许在函数内定义函数(尽管某些编译器可能提供它作为一个非标准的扩展)。

对于 C++ 也是如此,尽管较新的版本(C++0x 等)允许您定义匿名 lambda 函数。但这是不同的东西。

关于c++ - C 中的嵌套函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6095826/

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