提问人:Sachin 提问时间:4/9/2010 最后编辑:Antti Haapala -- Слава УкраїніSachin 更新时间:7/22/2020 访问量:114014
C 语言中的嵌套函数
Nested function in C
答:
不,它们在 C 中不存在。
它们在 Pascal 等语言中使用(至少)有两个原因:
- 它们允许在不污染命名空间的情况下进行功能分解。您可以定义一个公开可见的函数,该函数通过依赖一个或多个嵌套函数将问题分解为更小的逻辑部分来实现某些复杂的逻辑。
- 在某些情况下,它们简化了参数传递。嵌套函数可以访问外部函数范围内的所有参数以及部分或全部变量,因此外部函数不必将一堆局部状态显式传递到嵌套函数中。
不能在标准 C 中的另一个函数中定义一个函数。
您可以在函数内部声明函数,但它不是嵌套函数。
GCC 具有允许嵌套函数的语言扩展。它们是非标准的,因此完全依赖于编译器。
不,你不能在 中嵌套函数。最接近的方法是在另一个函数的定义中声明一个函数。但是,该函数的定义必须出现在任何其他函数体之外。C
例如
void f(void)
{
// Declare a function called g
void g(void);
// Call g
g();
}
// Definition of g
void g(void)
{
}
评论
g
嵌套函数不是 ANSI C 的一部分,但是,它们是 Gnu C 的一部分。
评论
正如其他人所回答的那样,标准 C 不支持嵌套函数。
在某些语言中,嵌套函数用于将多个函数和变量包含在一个容器中(外部函数),以便从外部看不到单个函数(不包括外部函数)和变量。
在 C 语言中,这可以通过将此类函数放在单独的源文件中来完成。 将 main 函数定义为全局函数,将所有其他函数和变量定义为静态函数和变量。 现在,在此模块之外仅可见 main 函数。
评论
outer
nested
outer
nested
int declared_in_outer
declared_in_outer
我之所以提到这一点,是因为现在很多人都在使用 C++ 编译器(例如 Visual C++ 和 Keil uVision)来做到这一点,所以你可以利用这个......
虽然在 C 中还不允许,但如果您使用的是 C++,则可以使用 C++11 中引入的 lambda 函数实现相同的效果:
void f()
{
auto g = [] () { /* Some functionality */ }
g();
}
评论
这不是 C 语言中的嵌套函数吗?( 函数 displayAccounts() )
我知道我本可以以不同的方式定义函数并传递变量和不传递的变量,但无论如何效果很好,因为我需要多次打印帐户。
(取自学校作业的狙击手)...
//function 'main' that executes the program.
int main(void)
{
int customerArray[3][3] = {{1, 1000, 600}, {2, 5000, 2500}, {3, 10000, 2000}}; //multidimensional customer data array.
int x, y; //counters for the multidimensional customer array.
char inquiry; //variable used to store input from user ('y' or 'n' response on whether or not a recession is present).
//function 'displayAccounts' displays the current status of accounts when called.
void displayAccounts(void)
{
puts("\t\tBank Of Despair\n\nCustomer List:\n--------------");
puts("Account # Credit Limit\t Balance\n--------- ------------\t -------");
for(x = 0; x <= 2; x++)
{
for(y = 0; y <= 2; y++)
printf("%9d\t", customerArray[x][y]);
puts("\n");
}
}
displayAccounts(); //prints accounts to console.
printf("Is there currently a recession (y or n)? ");
//...
return 0;
}
评论
为了回答第二个问题,有一些语言允许定义嵌套函数(可以在此处找到列表:nested-functions-language-list-wikipedia)。
在 JavaScript 中,这是最著名的语言之一,嵌套函数(称为闭包)可能是:
- 在对象的构造函数中创建类方法。
- 实现私有类成员以及 setter 和 getter 的功能。
- 不要污染全局命名空间(当然,每种语言都适用)。
仅举几例......
或者你可以聪明一点,利用预处理器来发挥你的优势():source.c
#ifndef FIRSTPASS
#include <stdio.h>
//here comes your "nested" definitions
#define FIRSTPASS
#include "source.c"
#undef FIRSTPASS
main(){
#else
int global = 2;
int func() {printf("%d\n", global);}
#endif
#ifndef FIRSTPASS
func();}
#endif
评论