为什么这个C ++代码片段分段错误? [英] Why does this C++ code-snippet segmentation fault?

查看:100
本文介绍了为什么这个C ++代码片段分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< iostream> 
using namespace std;

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

int main(){
recur(10);
return 0;
}


解决方案

  1 and recur( -  x); 

相当于

  recur( -  x); 

显然,你正在进行无限递归调用,导致堆栈溢出,

猜测是指

  - X); 

只有当x不为零时才进行递归调用。


#include <iostream>
using namespace std;

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

int main() {
    recur(10);
    return 0;
}

解决方案

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.

这篇关于为什么这个C ++代码片段分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆