C语言 C中的嵌套函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2608158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:08:09  来源:igfitidea点击:

Nested function in C

cfunctionnested

提问by Sachin Chourasiya

Can we have a nested function in C? What is the use of nested functions? If they exist in C does their implementation differ from compiler to compiler?

我们可以在 C 中有一个嵌套函数吗?嵌套函数有什么用?如果它们存在于 C 中,它们的实现是否因编译器而异?

回答by James McNellis

You cannot define a function within another function in standard C.

你不能在标准 C 的另一个函数中定义一个函数。

You can declarea function inside of a function, but it's not a nested function.

您可以在函数内部声明函数,但它不是嵌套函数。

gcc has a language extension that allows nested functions. They are nonstandard, and as such are entirely compiler-dependent.

gcc 有一个允许嵌套函数的语言扩展。它们是非标准的,因此完全依赖于编译器。

回答by Marcelo Cantos

No, they don't exist in C.

不,它们在 C 中不存在。

They are used in languages like Pascal for (at least) two reasons:

它们在 Pascal 等语言中使用(至少)有两个原因:

  1. They allow functional decomposition without polluting namespaces. You can define a single publicly visible function that implements some complex logic by relying one or more nested functions to break the problem into smaller, logical pieces.
  2. They simplify parameter passing in some cases. A nested function has access to all the parameters and some or all of the variables in the scope of the outer function, so the outer function doesn't have to explicitly pass a pile of local state into the nested function.
  1. 它们允许在不污染命名空间的情况下进行功能分解。您可以定义一个公开可见的函数,通过依赖一个或多个嵌套函数将问题分解为更小的逻辑部分来实现一些复杂的逻辑。
  2. 在某些情况下,它们简化了参数传递。嵌套函数可以访问外部函数范围内的所有参数和部分或全部变量,因此外部函数不必显式地将一堆局部状态传递给嵌套函数。

回答by zoli2k

Nested functions are not a part of ANSI C, however, they are part ofGnu C.

嵌套函数不是ANSI C的一部分,但是,它们是Gnu C 的一部分

回答by CB Bailey

No you can't have a nested function in C. The closest you can come is to declare a function inside the definition of another function. The definition of that function has to appear outside of any other function body, though.

不,您不能在C. 最接近的是在另一个函数的定义中声明一个函数。但是,该函数的定义必须出现在任何其他函数体之外。

E.g.

例如

void f(void)
{
    // Declare a function called g
    void g(void);

    // Call g
    g();
}

// Definition of g
void g(void)
{
}

回答by Jon Green

I mention this as many people coding in C are now using C++ compilers (such as Visual C++ and Keil uVision) to do it, so you may be able to make use of this...

我提到这一点是因为很多用 C 编码的人现在都在使用 C++ 编译器(例如 Visual C++ 和 Keil uVision)来做这件事,所以你可以利用这个......

Although not yet permitted in C, if you're using C++, you can achieve the same effect with the lambda functions introduced in C++11:

尽管在 C 中还不允许,但如果您使用的是 C++,则可以使用 C++11 中引入的 lambda 函数实现相同的效果:

void f()
{
    auto g = [] () { /* Some functionality */ }

    g();
}

回答by PauliL

As others have answered, standard C does not support nested functions.

正如其他人所回答的那样,标准 C 不支持嵌套函数。

Nested functions are used in some languages to enclose multiple functions and variables into a container (the outer function) so that the individual functions (excluding the outer function) and variables are not seen from outside.

嵌套函数在某些语言中用于将多个函数和变量封装在一个容器(外层函数)中,以便从外部看不到单个函数(不包括外层函数)和变量。

In C, this can be done by putting such functions in a separate source file. Define the main function as global and all the other functions and variables as static. Now only the main function is visible outside this module.

C 中,这可以通过将这些函数放在单独的源文件中来完成。将 main 函数定义为 global ,将所有其他函数和变量定义为static。现在只有 main 函数在这个模块之外可见。

回答by kyriakosSt

To answer your second question, there are languages that allow defining nested functions (a list can be found here: nested-functions-language-list-wikipedia).

要回答您的第二个问题,有些语言允许定义嵌套函数(可以在此处找到列表:nested-functions-language-list-wikipedia)。

In JavaScript, which is one of the most famous of those languages, some uses of nested functions (which are called closures) are:

在 JavaScript 中,这是其中最著名的语言之一,嵌套函数(称为闭包)的一些用途是:

  • To create class methods in constructors of objects.
  • To achieve the functionality of private class members along with setters and getters.
  • Not to pollute the global namespace (that goes for every language, of course).
  • 在对象的构造函数中创建类方法。
  • 实现私有类成员以及 setter 和 getter 的功能。
  • 不要污染全局命名空间(当然,这适用于每种语言)。

to name a few...

仅举几例...

回答by AnArrayOfFunctions

Or you can be smart about it and use the preprocessor in your advantage (source.c):

或者你可以聪明一点,使用你的优势 ( 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

回答by midnightCoder

is this not a nested function in C? ( the function displayAccounts() )

这不是 C 中的嵌套函数吗?(函数 displayAccounts() )

I know I could have defined the function differently and passed variables and what not but anyhow works nicely as I needed to print the accounts multiple times.

我知道我可以用不同的方式定义函数并传递变量,但无论如何都可以很好地工作,因为我需要多次打印帐户。

(snipet taken from a school assignment)...

(摘自学校作业的片段)...

//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;
}