problem with recursive definitions

Hello wise C++ forum,

I'm aware that "ordinary" recursive definitions are allowed in C++, the most typical example being a factorial: fact(x)=x*fact(x-1) with the definition 0!=1.

What about two-fold recursive definitions? (No longer talking factorials, just generally now.) The program below will not compile. It suffers a kind of chicken-and-egg problem that other languages don't suffer from.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <stdio.h>

int foo (int arg) {
	std::cout << "foo: " << arg << "\n";
	if ( arg == 0 ) { return 0; } else { return baz(arg-1); }
}


int baz (int arg) {
	std::cout << "baz: " << arg << "\n";
	if ( arg == 0 ) { return 0; } else { return foo(arg-1); }
}

int main() {
	std::cout << foo(6) << "\n";
	return 0;
}


To make the above point, the following QB64 program, identical in essence to the one above, compiles and works perfectly. Funny enough, QB64 sits on top of the gcc compiler, the same one I'm using for the C++ attempt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PRINT foo(6)

END

FUNCTION foo (arg)
PRINT "foo"; arg
IF arg = 0 THEN temp = 0 ELSE temp = baz(arg - 1)
foo = temp
END FUNCTION

FUNCTION baz (arg)
PRINT "baz"; arg
IF arg = 0 THEN temp = 0 ELSE temp = foo(arg - 1)
baz = temp
END FUNCTION


How do I resolve this issue? Thanks in advance.
Last edited on
Like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <stdio.h>

int baz (int arg); // Note: prototype here

int foo (int arg) {
	std::cout << "foo: " << arg << "\n";
	if ( arg == 0 ) { return 0; } else { return baz(arg-1); }
}


int baz (int arg) {
	std::cout << "baz: " << arg << "\n";
	if ( arg == 0 ) { return 0; } else { return foo(arg-1); }
}

int main() {
	std::cout << foo(6) << "\n";
	return 0;
}
Thanks very much coder777, this isn't the first time you bailed me out of a bind, either! Take care.
Topic archived. No new replies allowed.