13

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,

make
  • 755
  • 7
  • 21
  • 37
  • 1
    This doesn't really merit an 'answer'. "Yes." The caveat is the function is scoped, so you can only refer to it by name inside of the given function. You can still make a function pointer that points to it and toss that around elsewhere, though. – Conspicuous Compiler Feb 13 '10 at 06:03
  • Yes! you might be right that it doesn't really merit an 'answer' but when we try to solve for hours, we look for any solution ... I have never done it but I am lloking for a help to solve my problem ... thanks! – make Feb 13 '10 at 06:16
  • 4
    @Conspicuous Compiler: it may or may not merit an answer, but the answer certainly isn't a simple "yes". – Michael Burr Feb 13 '10 at 06:28
  • This is related to http://stackoverflow.com/questions/2256444/how-to-write-pthread-create-on-the-same-function – bk1e Feb 13 '10 at 16:03
  • Does this answer your question? [Can we have functions inside functions in C++?](https://stackoverflow.com/questions/4324763/can-we-have-functions-inside-functions-in-c) – pavel Nov 12 '19 at 19:36

15 Answers15

31

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
  • 134,909
  • 25
  • 265
  • 421
  • 6
    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 :) – Sebastian Mach Feb 13 '10 at 06:40
  • Darn! I never knew struct or class definitions were legal inside of a function! Potatoswatter! You win 'C++ guru master' award. –  Feb 13 '10 at 14:04
  • Note that C++11 lambda functions are just shorthand for this trick, including the part about giving it a constructor and passing [references to] local variables. – Potatoswatter May 11 '12 at 07:53
7

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

Xorlev
  • 8,561
  • 3
  • 34
  • 36
6

C — Yes for gcc as an extension.

C++ — No.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
5

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)

Community
  • 1
  • 1
  • 1
    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. – mpen Feb 13 '10 at 06:11
  • @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 Feb 13 '10 at 06:20
  • 2
    @Mark: also note that the x could be a hexadecimal number, allowing it to jump up to F. – Sebastian Mach Feb 13 '10 at 06:42
  • 1
    "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 Feb 13 '10 at 12:21
  • Steve i tried it out and 2010b2 does have this. Time to edit my answer. –  Feb 13 '10 at 13:49
  • @phresnel technically it be C++0xA (assuming 2010) or C++0x7DA –  Feb 13 '10 at 13:56
  • @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! –  Feb 13 '10 at 18:36
5

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
  • 3,285
  • 17
  • 17
  • 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 Feb 13 '10 at 17:21
4

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
  • 24,725
  • 16
  • 62
  • 87
3

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
  • 7,598
  • 6
  • 38
  • 61
3

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
  • 109,094
  • 6
  • 73
  • 101
  • 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) –  Feb 13 '10 at 16:19
3
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
  • 53,214
  • 7
  • 75
  • 105
  • 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 Feb 13 '10 at 17:29
  • Just replace the body of local_foo with your thread function. – MSN Feb 13 '10 at 17:37
2

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
  • 1,338
  • 1
  • 10
  • 17
  • 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 Feb 13 '10 at 17:20
1

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
  • 830
  • 8
  • 10
  • 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 Feb 13 '10 at 06:19
  • @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 Feb 13 '10 at 07:02
  • thanks! my problem is here : http://stackoverflow.com/questions/2256444/how-to-write-pthread-create-on-the-same-function , thanks again – make Feb 13 '10 at 17:23
1

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

caf
  • 233,326
  • 40
  • 323
  • 462
1

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
  • 476,176
  • 80
  • 629
  • 1,111
1

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

zaharpopov
  • 16,882
  • 23
  • 75
  • 93
1

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
  • 333,147
  • 50
  • 533
  • 760