see the code below, I define a function in another function,
void test1(void)
{
void test2(void)
{
printf("test2\n");
}
printf("test1\n");
}
int main(void)
{
test1();
return 0;
}
this usage is odd,is it a usage of c89/c99 or only a extension of gcc (I used gcc 4.6.3 in ubuntu 12 compiled). I run this code and it output "test2" and "test1".test2 can be only called in test1.
What's more,what's the common scene of this usage or what does this usage used for?
If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.
You cannot define a function within another function in standard C. You can declare a function inside of a function, but it's not a nested function. gcc has a language extension that allows nested functions.
A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined.
Yes, this is a GCC extension.
It's not C, it's not portable, and thus not very recommended unless you know that GCC will
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With