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?
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.
As written, it's not legal C++. You can, however, define
a class within a function, and define functions in that class.
But even then, in pre C++11, it's still only lexical nesting;
the class you define does not "capture" any of the context of
the outer function (unless you implement the capture
explicitly); in a true nested function, the nested function can
access local variables in the outer function. In C++11, you
can define a lambda function, with automatic capture.
The reason C and C++ never adopted nested functions is because
in order to make capture work, you need additional information,
with the result that a pointer to function becomes more complex.
With the result that either you cannot take the address of the
nested function (lack of orthogonality), a pointer to a nested
function is incompatible with a normal pointer to a function
(which ends up requiring too many external details to perculate
out), or all pointers to functions have the extra information
(and you pay for something you don't use most of the time).
http://gcc.gnu.org/onlinedocs/gcc-3.0.2/gcc_5.html#SEC71
Nested functions explanation.
Nested functions are only allowed in C but are seldomly used because they are visible within that function scope only. However if you want to workaround nested functions you can do something like this
#include<stdio.h>
typedef void (*fptr)(void);
fptr test1(void) {
void test2(void) {
printf("test2\n");
}
printf("test1\n");
return test2;
}
int main(void) {
void (*f)(void);
f = test1();
f();
return 0;
}