Having trouble with functions

I understand that to be able to invoke (is it said that way?) a function you have to have declared it before, so the structure would be something like:

Function 1.2{
}

Function 1.1{
}

Function 1{
Function 1.1
Function 1.2
}

main(){
Function 1
}



But what if I want to invoke function 1 from function 1.1?

Like a "Back" button? Because this is not a linear program, I want it to be able to return to the main menu then go elsewhere etc


Is it possible? Do I have to create new files or to ivoke it like "project.function1();"?
Last edited on
1
2
3
4
5
6
7
8
9
void foo();

void bar(){
    foo();
}

void foo(){
    bar();
}

Note that pressing a "back" button is not analogous to calling a function. When you press a back button the page you're currently on is closed and the program displays a previous page in its place. When you call a function B from function A, function A is still "active". You might want to rethink your design.
Yes, I think I can get it, but still can I alternate from one function to another? May I separate them in different files and execute each one when needed? (new to programming, sorry Dx)
Whether they are in separate files or in the same file makes no difference as far as the execution model is concerned.
What you probably want is some kind of state machine. Displaying page A would be one state and displaying page B would be another state.
Take a look at this SO answer: https://stackoverflow.com/a/133361
Last edited on
Lets consider the general case. A program contains 2 functions A and B. Each function must call the other. This is an example of recursion. More specifically, it is an example of what is called "Direct Recursion", where A calls B and B calls A. (In "Indirect recursion", A calls B, B calls C and C calls A, completing the recursive call).

Of course in recursion, there must be some way to terminate the recursion; else the program would end up in an infinite loop. To prevent this, the functions must include a terminating decision - which calls the other function only if a condition is satisfied.

The question is how to declare and define the functions. In C++ (and C), each entity must be declared before it is used. A definition is itself a declaration. But if A calls B and B calls A, we have a problem. One function call would occur before the compiler sees its declaration.

The solution is to declare the functions separately, before they are defined:

1
2
3
/// declarations ...
void A();
void B();


Then, include the definitions:

1
2
3
4
5
6
7
8
9
10
11
/// definitions ...
void A()
{
    /// ...
}

void B()
{
    /// ...
}


Then, the compiler sees the declarations of all functions, before either is invoked and so won't issue a compilation error.
Last edited on
Oh right I got it, IT WORKS! Thank you!
Registered users can post here. Sign in or register to post.