Is it legal to have functions within functions?

This is a discussion on Is it legal to have functions within functions? within the C++ Programming forums, part of the General Programming Boards category; Same question as above. Is it legal to have functions within functions, within functions, within functions, to the x power?...

  1. #1
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827

    Question Is it legal to have functions within functions?

    Same question as above. Is it legal to have functions within functions, within functions, within functions, to the x power?

  2. #2
    Not stupid, just stupider yaya's Avatar
    Join Date
    May 2007
    Location
    Earthland
    Posts
    204
    What do you mean by "have"? You can call a function from within a function but you can't decalare/initialise a function from a function.

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    What would be the point?
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  4. #4
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by yaya View Post
    What do you mean by "have"? You can call a function from within a function but you can't decalare/initialise a function from a function.
    I was asking basically what you just answered...i.e. if I could declare/initialise a function within another function.
    Damn! That sucks...I was hoping I could.
    The reason is, because I wanted to have a function (of "protected" status) inside a class, for the purpose of adding members to the class from outside the class, if you catch my drift...
    I figured if I did something like this, it would work:

    Code:
    class main_window_form //declare a class for the main window of the form, which will store all of the different 'parts' of the main window
    {
        public:
          main_window_form() //this will be the constructor of the class
          ~main_window_form() //this will be the desctructor for the class
        protected:
          char menu_bar; //declare variable to hold the *names* of the menus of the program, which will be clickable
          void add_members_to_class_function(void); //declare function of "protected" type of the class for the purpose of adding members to class
    
    };
          //do not forget the trailing semi-colon
    
      main_window_form::main_window_form(add_members_to_class_function(void)) //modify prototype of named function in class
       { //BEGIN brace for add_members_to_class_function
    
        void function_to_declare_variables_of_class() //declare function within that function for the sole purpose of declaring variables
          {
          char menu_bar; //modify the "menu_bar" variable which is stored in the class as a private member
          char file_menu; //declare File menu variable (which will store the parts of the File menu visible to the user)
          char edit_menu; //declare Edit menu variable (which will store the parts of the Edit menu visible to the user)
          char slide_show_menu; //declare Slide Show menu variable (which will store the parts of the Slide Show menu visible to the user)
          char menu_bar_array[4]; //declare menu_bar array (for storing the menus, which will be three)
          }
    The idea here was to have a hierarchy of functions, each of which I wanted to store inside the class called "main_window_form", but I was hoping if I wanted to add members to the class later on, I could have a function outside the class which could be used for that purpose, to keep my program as clean as possible, and readable. Now, I'm sure there's other ways to do that, but that's the first way that came to mind of how to accomplish it. But everyone feel free to offer your thoughts.
    Last edited by Programmer_P; 05-24-2009 at 10:45 PM.

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    If you need to add variables to the class, then you can't use a function anyways, since the variables inside the function will disappear when the function returns.

    The most obvious way to add variables to a class is to make a derived class, inheriting from the original class.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Is it legal to have functions within functions, within functions, within functions, to the x power?
    No, it's not legal if you want to do it directly:
    Code:
    #include <iostream>
    
    int main()
    {
        void foo()
        {
            std::cout<<"Foo!\n";
        }
    
        foo();
    }
    Can you do it? Yes, thanks to the magic of classes and operator overloading. And the result isn't much more verbose than the previous example:
    Code:
    #include <iostream>
    
    int main()
    {
        struct foo {
            void operator()()
            {
                std::cout<<"Foo!\n";
            }
        };
    
        foo()();
    }
    >What would be the point?
    Limiting the scope of a function can be useful and adds flexibility in structuring your code. It's not much different conceptually from nested classes.
    My best code is written with the delete key.

  7. #7
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by Prelude View Post
    >Is it legal to have functions within functions, within functions, within functions, to the x power?
    No, it's not legal if you want to do it directly:
    Code:
    #include <iostream>
    
    int main()
    {
        void foo()
        {
            std::cout<<"Foo!\n";
        }
    
        foo();
    }
    Can you do it? Yes, thanks to the magic of classes and operator overloading. And the result isn't much more verbose than the previous example:
    Code:
    #include <iostream>
    
    int main()
    {
        struct foo {
            void operator()()
            {
                std::cout<<"Foo!\n";
            }
        };
    
        foo()();
    }
    >What would be the point?
    Limiting the scope of a function can be useful and adds flexibility in structuring your code. It's not much different conceptually from nested classes.
    Ok, so what you're saying basically is create a structure inside int main() and inside that structure create the other functions I need? Would the same technique work if the function was not int main()?
    Also, I noticed you used double parentheses in the last example, i.e.
    Code:
    ()()
    instead of just
    Code:
    ()
    Why is that?
    Last edited by Programmer_P; 05-25-2009 at 10:24 AM.

  8. #8
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Quote Originally Posted by Programmer_P View Post
    Ok, so what you're saying basically is create a structure inside int main() and inside that structure create the other functions I need? Would the same technique work if the function was not int main()?
    Yes.

    Also, I noticed you used double parentheses in the last example, i.e.
    Code:
    ()()
    instead of just
    Code:
    ()
    Why is that?
    You first have to create an object (explicit constructor call, foo()) and then you can call the function call operator on it, so it's foo()().

    That said, I wouldn't look kindly on such code. The correct way to privatize functionality is by putting it into its own file.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  9. #9
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Quote Originally Posted by CornedBee View Post
    Yes.



    You first have to create an object (explicit constructor call, foo()) and then you can call the function call operator on it, so it's foo()().

    That said, I wouldn't look kindly on such code. The correct way to privatize functionality is by putting it into its own file.
    Well, that's what I was already planning to do, i.e. have each major function in its own file, which I then include in the main source code file. But I was hoping I could have a function within the main.cpp file that would be part of the class "main_window_form" for the purpose of adding variables to the class.
    I guess I'll have to try the method matsp suggested, i.e. use a derived class for adding variables.
    Thanks everyone for your help. I really appreciate it.

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Aside from the legality, a function can NEVER add variables to a class.

    [At least not if we tgalk regular variables - you could of course make your own dynamic variables (e.g a map or vector storing pairs of "name" and "value"), but I doubt that is what you actually meant].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  11. #11
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Ok, it seems I may have to forget the whole "add variables to class from outside the class" idea, and just add them the standard way, i.e. directly.
    The reason I was wanting to do it was because I thought it might be more readable if I had most of the variables for the program I'm writing in its own block of code. But nevermind...that's what comments are for, I guess. So I can keep track of whatever the hell it is that I wrote so far, and not forget what I was thinking at the time that I wrote it.

  12. #12
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    Quote Originally Posted by Programmer_P View Post
    Ok, it seems I may have to forget the whole "add variables to class from outside the class" idea, and just add them the standard way, i.e. directly.
    The reason I was wanting to do it was because I thought it might be more readable if I had most of the variables for the program I'm writing in its own block of code. But nevermind...that's what comments are for, I guess. So I can keep track of whatever the hell it is that I wrote so far, and not forget what I was thinking at the time that I wrote it.
    That's what variable names are for imo
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  13. #13
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827

    Thumbs up

    Quote Originally Posted by ಠ_ಠ View Post
    That's what variable names are for imo
    That too.

  14. #14
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,235
    Quote Originally Posted by cpjust View Post
    What would be the point?
    We're not talking about standard C or C++, but nested functions are provided as an extension by several compilers. The point is two-fold. First, limitation of the scope of the name (which can be accomplished in other more standard ways, at least in C++).

    Second is inheritance of the local scope itself. In all implementations of nested C/C++ functions I've seen, the inner function has access to the local variables of the outer function.

    This imposes some strange requirements on the compiler. How do you pass a pointer to a nested function while still allowing access to the enclosing function's local variables? It's pretty awful, and involves writing code onto the stack.

    IMO, the feature is simply not useful enough to justify 1) writing grossly nonstandard code and 2) forcing the stack to be executable just to implement a strange corner case.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Void Functions Help
    By bethanne41 in forum C++ Programming
    Replies: 1
    Last Post: 05-09-2005, 05:30 PM
  2. Functions and Classes - What did I do wrong?
    By redmage in forum C++ Programming
    Replies: 5
    Last Post: 04-11-2005, 11:50 AM
  3. calling functions within functions
    By edd1986 in forum C Programming
    Replies: 3
    Last Post: 03-29-2005, 02:35 AM
  4. Factory Functions HOWTO
    By GuardianDevil in forum Windows Programming
    Replies: 1
    Last Post: 05-01-2004, 01:41 PM
  5. Shell functions on Win XP
    By geek@02 in forum Windows Programming
    Replies: 6
    Last Post: 04-19-2004, 05:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21