#include <iostream>
using namespace std;
int recur(int x) {
1 and recur(--x);
cout << x;
return x;
}
int main() {
recur(10);
return 0;
}
views:
171answers:
4Thats an infinite recursion. So it will seg fault when it runs out of stack space.
It doesn't have a termination condition for the recursion, and so will recurse until you run out of stack space.
1 and recur(--x);
is equivalent to
recur(--x);
Clearly you are making infinite recursive calls which leads to stack overflow followed by segmentation fault.
I guess you meant
x and recur(--x);
which makes the recursive call only when x is non-zero.
recur
is an infinite loop; you need to put a base condition on there so it stops calling itself.
E.g. (at the top of the function) if (x <= 0) return 0;
Also, what's the point of the 1 and
? It's a no-op... maybe you meant x and
, which would stop the recursion when x
reached 0
, provided you only ever called recur
with a positive number (negative values would still cause the infinite loop).