0

I have two functions that is dependent on each other, but the order of the function in C++ limit my ability to write reusable codes. For example let say, I want to use functionA in a functionB then

functionB has to be above functionA.

but what if

functionB is using functionA and functionA is using functionB as well? it will gives error

Here's the code, and the order of the functions in c++

void getAnswer(string answer) {

            mainProgram();

}

void mainProgram() {
   getAnswer("awesome");

}

int _tmain(int argc, _TCHAR* argv[])
{   

    mainProgram();


    return 0;
}

As you can see mainProgram() is using getAnswer() function and vice versa.

I can just solve this problem by deleting the getAnswer() function and simply throw every code from getAnswer() to mainProgram() but the problem with that , is I will write a repetitive code for about 5 times, and it will look really messy.

airsoftFreak
  • 1,450
  • 5
  • 34
  • 64

3 Answers3

5

You need to forward-declare your function:

//forward declaration
void mainProgram();

void getAnswer(string answer) {
    //sees the declaration above, doesn't need the definition
    mainProgram();
}

//now we define the function
void mainProgram() {
   getAnswer("awesome");
}

This kind of thing should be covered in your introductory book. If you don't have a good introductory book, get one.

Also note that you will need to terminate this mutual recursion at some point.

Community
  • 1
  • 1
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
3

What you are looking for is called forward declaration.

Define the names and parameters of the functions first, and then declare their body. This allows two functions to be dependent on each other.

void mainProgram(); // this is a declaration of your function.

void getAnswer(string answer) // the body of the function which can call the declared function.
{
    mainProgram();
}

void mainProgram() // the body of the function which was declared earlier.
{
    getAnswer("awesome");
}
therainmaker
  • 4,253
  • 1
  • 22
  • 41
0

In this case it is infinite of function calling .However if your not sure about order function calling and it's declaration, use forward declare in the beginning of the file.

Venkata Naidu M
  • 351
  • 1
  • 6