Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function definition inside another function definition: is it valid?

Tags:

c

function

see this code

#include<stdio.h>

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

this coed works fine and doesnt give any warning and error. I am not getting why this happening ? here i have written one function definition inside other function definition so is it valid?

EDIT: if yes then is there any usage of this ?

Why gcc needs to add this features as extension..there should be any usage of this isnt it ?!

like image 382
Jeegar Patel Avatar asked Nov 11 '11 07:11

Jeegar Patel


2 Answers

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.

like image 193
David Heffernan Avatar answered Sep 19 '22 01:09

David Heffernan


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

like image 37
Romi Halasz Avatar answered Sep 19 '22 01:09

Romi Halasz