递归函数错误 Dev-C++
recursive function error Dev-C++
我有以下代码顺序搜索在Visual C++中完美运行
#include<iostream>
using namespace std;
int seqSearch(int list[], int length, int item)
{
int index = length-1;
if (index < 0)
return -1;
if (list[index] == item)
return (index);
else seqSearch(list, index, item);
} // end seqSearch
int main ()
{
int const length = 10;
int item;
int list[10] = { 2, 3, 4, 5, 20, 40, 80, 45, 99, 0};
cout << "Please enter the value to be searched: ";
cin>> item;
if (seqSearch(list, length, item) == -1) cout << "Item not found." << endl;
else cout <<"Item found at position: " << seqSearch(list, length, item) << " of list *Note: (first index of list start at 0)" << endl;
system("pause");
return 0;
}
但是在 Dev-C++ 中它总是显示结果 0,我尝试调试并查看索引是否正确,但为什么它显示 0?为什么我们在VC++和Dev-C++之间有这种差异?
函数
int seqSearch
有一个代码路径,else seqSearch(list, index, item);
不返回任何内容。将其更改为else return seqSearch(list, index, item);
应该可以解决问题。
现在挖得有点深。
从 n2960 草案:
§ 6.6.3/2
从函数末尾流出等效于没有值的返回;这会导致值返回函数中出现未定义的行为。
因此,根据标准,这是一种未定义的行为。
深入挖掘:
- 为什么不从非 void 函数返回不是编译器错误?
以确定是否所有代码路径都返回是一项困难的操作,不需要实现来检查这一点。
- 为什么代码在 VC++ 中功能正常
这依赖于体系结构和调用约定。尝试以下代码:
#include <iostream>
int fun (int v)
{
int a = v;
}
int main ()
{
std::cout << fun(5) << std::endl;
}
在不同的编译器上,函数fun
返回0
或传递给它的任何值。基本上它可以返回上次计算表达式的值。
正确的方法定义应该是
int seqSearch(int list[], int length, int item)
{
int index = length-1;
if (index < 0)
return -1;
if (list[index] == item)
return (index);
else return seqSearch(list, index, item);
}
您错过了返回语句。理想情况下,编译器应该警告您,但我不太熟悉 Dev-CPP 使用的版本。
相关文章:
- 请发现它在 dev 中工作的错误,但在 hackerrank 中不起作用
- 我正在使用dev c ++,但收到错误(C++98'array'必须由构造函数初始化)
- DEV C++ 第 69 行 [错误] ISO "for" 范围更改了"i"的名称查找 [-允许]
- dev在试图从dev c++mingw 4.8.1中的文件读取时接收分段错误
- 从 win 7 升级到 Win 10 后,出现 Dev-C++ makefile.win 编译错误
- 开发如何解决错误193:%1不是Dev C 中的Win32应用程序
- 我正在尝试在Ubuntu 14上安装libgtk2.0-dev,但出现了一些错误
- 在使用 Dev-C++5.11 的C++程序中编译了错误的文件
- dev -c - [构建错误] [main.o]错误2816
- 开发人员在Dev C 中编译代码时,我会收到此错误:[错误] ID返回1退出状态
- 管道到 /dev/null 时出现未指定的iostream_category错误(iOS::badbit 问题?
- 尝试使用 dev-C++ 创建.exe时出现错误 255
- 堆栈和队列在 Dev-C++ 中给出错误
- Dev-C++给出 Makefile.win 和 g++ 停止的错误
- dev-c++ 编译器错误没有匹配函数
- dev c++没有突出显示语法错误和错误
- 我有libstdc++6-dev,但仍然有stl链接错误
- 递归函数错误 Dev-C++
- 尝试在 dev C++ win7 中编译 winsock 程序 - 错误
- dev 代码::Blocks/ Dev-c++: 错误: iostream: 没有这样的文件或目录