问题
#include <iostream>
using namespace std;
int recur(int x) {
1 and recur(--x);
cout << x;
return x;
}
int main() {
recur(10);
return 0;
}
回答1:
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.
回答2:
Thats an infinite recursion. So it will seg fault when it runs out of stack space.
回答3:
It doesn't have a termination condition for the recursion, and so will recurse until you run out of stack space.
回答4:
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).
来源:https://stackoverflow.com/questions/2809014/why-does-this-c-code-snippet-segmentation-fault