tags:

views:

556

answers:

15

hi

Could someone please tell me if this is possible in C or C++?

void fun_a();
//int fun_b();
...
main(){
   ...
   fun_a();
   ...
   int fun_b(){
     ...
   }
   ...
} 

or something similar, as e.g. a class inside a function?

thanks for your replies,

A: 

It is not possible to declare a function within a function. You may, however, declare a function within a namespace or within a class in C++.

JonM
thanks! the problem is that I am using MexFunction() as a main function and I have a problem to include multi-threads on it. thanks again!
make
@mk: you might want to post a another question specifically about your multi-thread problem (with more details). I'm not sure what multi-threading would have to do with nesting functions (rather - I'm not sure why multi-threading would necessitate nested functions).
Michael Burr
thanks! my problem is here : http://stackoverflow.com/questions/2256444/how-to-write-pthread-create-on-the-same-function , thanks again
make
+6  A: 

C++ does not support nested functions, however you can use something like boost::lambda.

Xorlev
thanks! I want really to solve my problem without using boost libraries
make
+3  A: 

No but in C++0x you can http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions which may take another few years to fully support. The standard is not complete at the time of this writing.

-edit-

Yes

If you can use MSVC 2010. I ran the code below with success

void test()
{
 []() { cout << "Hello function\n"; }();
 auto fn = [](int x) -> int { cout << "Hello function (" << x << " :))\n"; return x+1; };
 auto v = fn(2);
 fn(v);
}

output

Hello function
Hello function (2 :))
Hello function (3 :))

(I wrote >> c:\dev\loc\uniqueName.txt in the project working arguments section and copy pasted this result)

acidzombie24
Haha.. I just realized they missed their target of completing the standard by 2010. "C++0x" is no longer an appropriate term. They'll have to redub it "C++1x" or "C++xx"... pretty sad that it's taken them over 10 years.
Mark
@Mark: "Even though the standard will not be delivered before 2010, we have chosen to keep the informal designation C++0X, so as not to introduce any additional confusion." — http://groups.google.com/group/comp.std.c++/browse_thread/thread/5aa7115a76eaeb33
KennyTM
@Mark: also note that the x could be a hexadecimal number, allowing it to jump up to F.
phresnel
"may take another few years to fully support". Or "are already implemented and just waiting for the standard to be finalised", depending what compiler you use. It's in the VS2010 previews, and there's a branch of GCC working on it as we speak.
Steve Jessop
Steve i tried it out and 2010b2 does have this. Time to edit my answer.
acidzombie24
@phresnel technically it be C++0xA (assuming 2010) or C++0x7DA
acidzombie24
thanks ! does gcc support this?
make
@mk: Not sure. It may be in 4.5 http://gcc.gnu.org/projects/cxx0x.html#lambdas It shows 4.5 as active development (no mentioned of 4.4) and i do see a version of 4.5 in the snapshot so you may download and try your luck ;). GL!
acidzombie24
+5  A: 

C — Yes for gcc as an extension.

C++ — No.

KennyTM
nice! i didn't know this existed.
Robert Karl
+1 to bad this isnt carried into c++!
acidzombie24
thanks! The program I am running contain C and C++ code
make
A: 

Not in standard C, but gcc and clang support them as an extension. See the gcc online manual.

caf
A: 

Though C and C++ both prohibit nested functions, a few compilers support them anyway (e.g., if memory serves, gcc can, at least with the right flags). A nested functor is a lot more portable though.

Jerry Coffin
+3  A: 

The term you're looking for is nested function. Neither standard C nor C++ allow nested functions, but GNU C allows it as an extension. Here is a good wikipedia article on the subject.

I. J. Kennedy
+3  A: 

Clang/Apple are working on 'blocks', anonymous functions in C! :-D

^ ( void ) { printf("hello world\n"); }

info here and spec here, and ars technica has a bit on it

Robert Karl
A: 

No nested functions in C/C++, unfortunately.

zaharpopov
+2  A: 

No, and there's at least one reason why it would complicate matters to allow it. Nested functions are typically expected to have access to the enclosing scope. This makes it so the "stack" can no longer be represented with a stack data structure. Instead a full tree is needed.

Consider the following code that does actually compile in gcc as KennyTM suggests.

#include <stdio.h>

typedef double (*retdouble)();

retdouble wrapper(double a) {
  double square() { return a * a; }

  return square;
}

int use_stack_frame(double b) {
  return (int)b;
}

int main(int argc, char** argv) {
  retdouble square = wrapper(3);
  printf("expect  9 actual %f\n", square());
  printf("expect  3 actual %d\n", use_stack_frame(3));
  printf("expect 16 actual %f\n", wrapper(4)());
  printf("expect  9 actual %f\n", square());
  return 0;
}

I've placed what most people would expect to be printed, but in fact, this gets printed:

expect  9 actual 9.000000
expect  3 actual 3
expect 16 actual 16.000000
expect  9 actual 16.000000

Notice that the last line calls the "square" function, but the "a" value it accesses was modified during the wrapper(4) call. This is because a separate "stack" frame is not created for every invocation of "wrapper".

Note that these kinds of nested functions are actually quite common in other languages that support them like lisp and python (and even recent versions of Matlab). They lead to some very powerful functional programming capabilities, but they preclude the use of a stack for holding local scope frames.

Mr Fooz
I know it isnt clear but i doubt op was asking if you can create a function in a function and call it outside of the function (it doesnt make sense for scope reasons as it is in a {} block and also for reasons you mentioned)
acidzombie24
+25  A: 

Wow, I'm surprised nobody has said yes! Free functions cannot be nested, but functors and classes in general can.

void fun_a();
//int fun_b();
...
main(){
   ...
   fun_a();
   ...
   struct { int operator()() {
     ...
   } } fun_b;

   int q = fun_b();
   ...
}

You can give the functor a constructor and pass references to local variables to connect it to the local scope. Otherwise, it can access other local types and static variables. Local classes can't be arguments to templates, though.

Potatoswatter
Note that C++0x (bah, I slowly begin to hate all those "note that in C++0x"-notes) local types will derive their linkage from the enclosing function, so then you will be able to put them to template argument lists :)
phresnel
@Potatoswatter: Good point.
Michael Burr
Darn! I never knew struct or class definitions were legal inside of a function! Potatoswatter! You win 'C++ guru master' award.
acidzombie24
thanks! can you please help me with this : http://stackoverflow.com/questions/2256444/how-to-write-pthread-create-on-the-same-function , thanks again
make
+1  A: 

You can nest a local class within a function, in which case the class will only be accessible to that function. You could then write your nested function as a member of the local class:

#include <iostream>

int f()
{
    class G
    {
    public:
        int operator()()
        {
            return 1;
        }
    } g;

    return g();
}

int main()
{
    std::cout << f() << std::endl;
}

Keep in mind, though, that you can't pass a function defined in a local class to an STL algorithm, such as sort().

int f()
{
    class G
    {
    public:
        bool operator()(int i, int j)
        {
            return false;
        }
    } g;

    std::vector<int> v;

    std::sort(v.begin(), v.end(), g);  //  Fails to compile
}

The error that you would get from gcc is "test.cpp:18: error: no matching function for call to `sort(__gnu_cxx::__normal_iterator > >, __gnu_cxx::__normal_iterator > >, f()::G&)' "

Josh Townzen
thanks! can you please help me with this : http://stackoverflow.com/questions/2256444/how-to-write-pthread-create-on-the-same-function , thanks again
make
+4  A: 

you can't create a function inside another function in C++.

You can however create a local class functor:

int foo()
{
   class bar
   {
   public:
      int operator()()
      {
         return 42;
      }
   };
   bar b;
   return b();
}

in C++0x you can create a lambda expression:

int foo()
{
   auto bar = []()->int{return 42;};
   return bar();
}
Rick
thanks! can you please help me with this : http://stackoverflow.com/questions/2256444/how-to-write-pthread-create-on-the-same-function , thanks again
make
A: 

As other answers have mentioned, standard C and C++ do not permit you to define nested functions. (Some compilers might allow it as an extension, but I can't say I've seen it used).

You can declare another function inside a function so that it can be called, but the definition of that function must exist outside the current function:

#include <stdlib.h>
#include <stdio.h>

int main( int argc, char* argv[])
{
    int foo(int x);

    /*     
    int bar(int x) {  // this can't be done
        return x;
    }
    */

    int a = 3;

    printf( "%d\n", foo(a));

    return 0;
}


int foo( int x) 
{
    return x+1;
}

A function declaration without an explicit 'linkage specifier' has an extern linkage. So while the declaration of the name foo in function main() is scoped to main(), it will link to the foo() function that is defined later in the file (or in a another file if that's where foo() is defined).

Michael Burr
+2  A: 
void foo()
{
    class local_to_foo 
    { 
         public: static void another_foo() 
         { printf("whatevs"); } 
    };
    local_to_foo::another_foo();
}

Or lambda's in C++0x.

MSN
thanks! can you please help me with this : http://stackoverflow.com/questions/2256444/how-to-write-pthread-create-on-the-same-function , thanks again
make
Just replace the body of local_foo with your thread function.
MSN