Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining function within a function in C [duplicate]

Tags:

c

Possible Duplicate:
Are nested functions a bad thing in gcc ?

As far as I know, C does not allow a function to be defined within other function. But the following code compiles and runs without any error in gcc. Can someone explain the reason why? See this also : http://ideone.com/AazVK

#include <stdio.h>

void val1( int x ) 
{
        void sig( int x ) {
                printf("%d\n",x*10);
        }
        sig(x);
}

int main()
{       
        void val2(int x) {
                x = x*10;
                val1(x);

                printf( "%d\n", x ); 
                if ( x < 10000 ) {
                        val2(x);                
                }
        }

        val2(20);

        return 0;
}
like image 858
kiesel-x Avatar asked Jan 16 '11 13:01

kiesel-x


People also ask

Can I define a function inside a function C?

Nested function is not supported by C because we cannot define a function within another function in C. We can declare a function inside a function, but it's not a nested function.

Can I define a function inside a function?

A function which is defined inside another function is known as inner function or nested functio n. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This process is also known as Encapsulation .

What is nesting of function in C?

A nested function is a function defined inside the definition of another function. It can be defined wherever a variable declaration is permitted, which allows nested functions within nested functions. Within the containing function, the nested function can be declared prior to being defined by using the auto keyword.

Can functions be nested?

Using a function as one of the arguments in a formula that uses a function is called nesting, and we'll refer to that function as a nested function.


1 Answers

gcc (but not g++) supports nested functions as a C language extension.

like image 107
Frédéric Hamidi Avatar answered Oct 13 '22 05:10

Frédéric Hamidi