views:

171

answers:

4
#include <iostream>
using namespace std;

int recur(int x) {
    1 and recur(--x);
    cout << x;
    return x;
}

int main() {
    recur(10);
    return 0;
}
+5  A: 

Thats an infinite recursion. So it will seg fault when it runs out of stack space.

Naveen
+2  A: 

It doesn't have a termination condition for the recursion, and so will recurse until you run out of stack space.

Andreas Brinck
+4  A: 
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.

codaddict
...and in a beautifully non-obvious way. Prefer the `if (x <= 0) return 0;` that tzaman suggested because it is more readable and is safer in the event that later code changes cause `x` to skip 0 on its way to negative infinity.
msw
+2  A: 

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).

tzaman
Negative values won't cause an infinite loop, but you will likely still blow your stack, so its basically the same thing.
Dennis Zickefoose
A recursive function isn't __looping,__ it's __recursing.__ Therefor it isn't an __endless loop,__ but an __endless recursion.__
sbi