Function definition inside another function definition: is it valid?

后端 未结 5 1323
广开言路
广开言路 2020-12-17 01:05

see this code

#include

int main()
{
    void test(void)
    {
        printf(\"test\");
        return;
    }
printf(\"main\");
return 0;
}
<         


        
相关标签:
5条回答
  • 2020-12-17 01:50

    I know that GCC has this as an extension. It's not, as far as I know, part of the standard.

    0 讨论(0)
  • 2020-12-17 01:52

    Joachim's answer about nested functions being a GCC extension is correct; you also asked if there is any usage of it: I've seen source code from hundreds of projects and never once seen anyone using this particular GCC extension.

    0 讨论(0)
  • 2020-12-17 01:54

    Nesting of function definitions relies on a GCC extension to work. It is not described by the standard.

    If you have any desire for your code to work with other compilers then you should refrain from using such techniques. What's more, if you collaborate with other developers, I predict that many of them will dislike the use of such non-standard constructs.

    I'm not expert with GCC but I'm fairly sure there are compiler options to disable extensions. This will allow you to get the compiler to make sure you are not writing code that won't compile with other compilers.


    Regarding your update there are uses for nested functions. They can aid encapsulation by restricting scope and visibility. However, there is no problem that cannot be solved perfectly adequately without nested functions which I think explains why they are a rarely used GCC peculiarity.

    0 讨论(0)
  • 2020-12-17 01:54

    Defining a nested function (i.e. inside another function) is valid, the only limitation is that the former function's scope is limited by the enclosing function. It's just like defining a local variable. You can find more information here: http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

    0 讨论(0)
  • 2020-12-17 01:57

    Yes we can define a function in other function. I have compiled below written lines in gcc and it ran successfully without showing an error.

    #include<stdio.h>;
    void main()
    {
        int sum()
        {
            int a=30, b=10, c=20, sum=0;
            sum=a+b+c;
            return sum;
        }
        int a;
        a=sum();
        printf("Sum = %d", a);
    }
    

    O/p:60

    0 讨论(0)
提交回复
热议问题