Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I define a function in another function?

Tags:

c++

c

gcc

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?

like image 294
Ezio Avatar asked May 16 '13 08:05

Ezio


People also ask

Is it possible to define a function in another function?

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.

Can a function be defined in another function in C?

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.

Can we define a function inside another function in Python?

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.

Can variables defined in a function be used in another function?

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.


1 Answers

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

  • Be the only compiler used to build your code
  • Will keep supporting this feature in future versions
  • Don't care about principle of least astonishment.
like image 72
unwind Avatar answered Oct 13 '22 09:10

unwind