Why can I define a function in another function?

c, c++, gcc

Solution

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.

Problem

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?

Original source