为什么这个 C++代码片段分段错误?
#include <iostream>
using namespace std;
int recur(int x) {
1 and recur(--x);
cout << x;
return x;
}
int main() {
recur(10);
return 0;
}
#include <iostream>
using namespace std;
int recur(int x) {
1 and recur(--x);
cout << x;
return x;
}
int main() {
recur(10);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是无限递归。所以当堆栈空间耗尽时就会出现段错误。
Thats an infinite recursion. So it will seg fault when it runs out of stack space.
相当于
显然您正在进行无限递归调用,这会导致堆栈溢出,然后出现分段错误。
我猜你的意思
是仅当 x 非零时才进行递归调用。
is equivalent to
Clearly you are making infinite recursive calls which leads to stack overflow followed by segmentation fault.
I guess you meant
which makes the recursive call only when x is non-zero.
它没有递归的终止条件,因此将递归直到用完堆栈空间。
It doesn't have a termination condition for the recursion, and so will recurse until you run out of stack space.
recur
是一个无限循环;您需要在那里放置一个基本条件,以便它停止调用自身。例如(在函数的顶部)
if (x <= 0) return 0;
另外,
1 和
有什么意义?这是一个无操作...也许您的意思是x 和
,当x
达到0
时,它会停止递归,前提是您只调用过recur
为正数(负值仍会导致无限循环)。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 meantx and
, which would stop the recursion whenx
reached0
, provided you only ever calledrecur
with a positive number (negative values would still cause the infinite loop).