Nested function in C

前端 未结 9 1582
眼角桃花
眼角桃花 2020-11-22 12:24

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?

相关标签:
9条回答
  • 2020-11-22 12:57

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

    0 讨论(0)
  • 2020-11-22 12:58

    No, they don't exist in C.

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

    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.
    0 讨论(0)
  • 2020-11-22 13:05

    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.

    E.g.

    void f(void)
    {
        // Declare a function called g
        void g(void);
    
        // Call g
        g();
    }
    
    // Definition of g
    void g(void)
    {
    }
    
    0 讨论(0)
提交回复
热议问题