'How to solve this indirect recursion error? [duplicate]

#include <iostream>
#include <stdio.h>
using namespace std;

void funB(int n){
    if (n>1){
    cout<<n<<" ";
    funA(n/2);
}
}
void funA(int m)
{
    if (m>0){
        cout<<m<<" ";
        funB(m-1);
        }
}

int main()
{
    funA(20);
    return 0;
}

For this code I am getting the following error:

prog.cpp: In function ‘void funB(int)’:
prog.cpp:8:13: error: ‘funA’ was not declared in this scope
     funA(n/2);
             ^

For this simple indirect recursion example, What is the possible error? I even tried changing the order of the functions.



Solution 1:[1]

Try this. What I have done is, I have just declared the funA before the definition of both functions just so that the compiler knows that there exists a function 'funA' which is being referred to. This is called forward declaration.

#include <iostream>
#include <stdio.h>
using namespace std;
void funA(int);
void funB(int n){
    if (n>1){
    cout<<n<<" ";
    funA(n/2);
}
}
void funA(int m)
{
    if (m>0){
        cout<<m<<" ";
        funB(m-1);
        }
}

int main()
{
    funA(20);
    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Suyash Krishna