how to made two nested procedures?

I wanna made a program which can call two nested procedures, but i don't know what I must made. Who can help me?
My program have main structure following
int cal1(int n,int m)
{
cal2(n,m);
}
int cal2(int n,int m)
{
cal1(n,m);
}
That is certainly legal... but what exactly are you trying to accomplish?

If cal1 calls cal2, and cal2 calls cal1... then your program will loop endlessly:
cal1->cal2->cal1->cal2->cal1->etc....

Your program will deadlock... until you run out of stack space, at which point it will crash.
As far as I can tell, you created an infinite loop, because the functions will just keep calling each other. You need to build in a check somehow to see whether one function should stop calling the other.

1
2
3
4
5
6
7
8
9
10
11
12
int cal1(int n,int m)
{
    //do something with n,m
    if (condition)
        cal2(n,m);
}
int cal2(int n,int m)
{
    //do something with n,m
    if (condition)
        cal1(n,m);
}
Last edited on
What you've done is mutual recursion.

But as Disch has already said, in your case the recursion carries on until you run of stack space.

With mutual (or indirect) recursion, as with (normal) direct recursion, you need a termination condition for it to be useful.

This contrived example illustrates how to use mutual recursion (stolen from:
Mutual recursion
http://en.wikipedia.org/wiki/Mutual_recursion )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <iomanip>
using namespace std;

bool is_even(unsigned int n);
bool is_odd(unsigned int n);

bool is_even(unsigned int n) {
    if (n == 0)
        return true;
    else
        return is_odd(n - 1);
}
 
bool is_odd(unsigned int n) {
    if (n == 0)
        return false;
    else
        return is_even(n - 1);
}

void test(unsigned int n) {
    cout << "value   = " << n << "\n";
    cout << "is_even = " << is_even(n) << "\n";
    cout << "is_odd  = " << is_odd(n)  << "\n";
    cout << "\n";
}

int main() {
    cout << boolalpha;

    test(3);
    test(8);

    return 0;
}


Andy
Last edited on
Topic archived. No new replies allowed.