PDA

View Full Version : functions within functions??



ayastona
April 23rd, 2009, 10:21 PM
int main()
{

MyFunction();

return 0;
}

void MyFunction()
{
void MySubFunction()
{
}
}

is it possible?

stroyan
April 23rd, 2009, 10:23 PM
C won't allow nested function definitions.
Pascal will allow it.

Npl
April 23rd, 2009, 11:11 PM
Not allowed in C or C++.
gcc allows it as extension tough (only for C, not for C++): Nested Functions (http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Nested-Functions.html)

CptPicard
April 24th, 2009, 12:38 AM
The gcc extension is really handy though, it makes writing callbacks with closure-like behaviour so much easier, not to mention safer...

eye208
April 24th, 2009, 09:02 AM
is it possible?
No, but you can define local function objects. Unlike local functions, it is safe to pass function objects as callbacks because their state is separate from the surrounding function.

Arndt
April 24th, 2009, 09:22 AM
C won't allow nested function definitions.
Pascal will allow it.

Some others will too. I don't know by heart, but look up what Python, Ruby, Perl, Javascript, Java and PHP do.

Reiger
April 24th, 2009, 12:49 PM
Anything which implements the lambda statement will do that: lambda calculus is theory behind a means of defining functions; each arbitrarily nested lambda statement is an anonymous function.

Also, in JavaScript functions are objects, and objects are functions. As a result passing functions around as well as nesting functions becomes trivial (altough you may get burnt for doing that on MSIE, there are/used-to-be memory leaks involved).

samjh
April 24th, 2009, 01:05 PM
http://en.wikipedia.org/wiki/Nested_function

mmix
April 24th, 2009, 01:13 PM
Not allowed in C or C++.
gcc allows it as extension tough (only for C, not for C++): Nested Functions (http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Nested-Functions.html)

It will be changed.
svn://gcc.gnu.org/svn/gcc/branches/cxx0x-lambdas-branch
http://gcc.gnu.org/projects/cxx0x.html#lambdas

http://gcc.gnu.org/wiki/MiddleEndLispTranslator

Npl
April 24th, 2009, 01:23 PM
It will be changed.
svn://gcc.gnu.org/svn/gcc/branches/cxx0x-lambdas-branch
http://gcc.gnu.org/projects/cxx0x.html#lambdas

http://gcc.gnu.org/wiki/MiddleEndLispTranslatorlamba functions (function objects) arent nested functions.
Nested functions are simpler and more restricted.

nvteighen
April 24th, 2009, 04:47 PM
gcc allows it but is non-standard.

Lambdas are actually something more than functions... They also set an environment that allows you to create new bindings. This is much clearer when using functional languages... if you just want to slip in a new variable in runtime, use a lambda.