C++ 函数中"Unreachable code"的说明
Explanation for "Unreachable code" within c++ function
目标是编写一个在数组中搜索值的函数。如果数组包含该值,则返回键所在的索引。如果数组不包含该值,则返回 -1
我有一个返回数组变量索引的 c++ 函数。我需要解释为什么我的代码部分(即 for 循环表达式中的"i++"(被我的 IDE 标记为"无法访问">
我尝试逐行调试代码,看看是否可以破译为什么 i++ 无法访问。我无法确定原因。但是,我怀疑这可能与我的"返回"声明有关
int main()
{
const int size = 4;
int array[] = { 345, 75896, 2, 543 };
int searchKey = 543;
std::cout << "Found at: " << search(array, size, searchKey);
return 0;
}
int search(int* array, int size, int searchkey)
{
while (1) {
std::cout << "Enter an Integer to search. Hit -1 to quit.n";
scanf("%d", &searchkey);
if (searchkey == -1) {
break;
}
for (int i = 0; i < size; i++) {
if (array[i] == searchkey) {
return 1;
}
else {
return -1;
}
}
}
}
如果数组中存在 searchKey,我希望该函数返回数组的索引,但它最终总是返回"-1">
for
循环不太正确。该函数在循环的第一次迭代中返回,而不考虑数组中第一项的值。如果第一项与搜索键匹配,则该函数返回 1。如果不是,则返回 -1。它永远不会触及数组中的第二项。
您需要删除else
部件。 仅在循环结束后返回 -1。
for(int i=0; i<size; i++){
if(array[i] == searchkey){
// Key was found. Return the index.
return i;
}
}
// Key was not found.
return -1;
代码中的逻辑决定在 for 循环中第一次返回 1 或 -1,因此它永远不会接触 i++。
您应该只在循环结束时返回 -1(搜索完成时(
for(int i=0; i<size; i++){
if(array[i] == searchkey){
// return the INDEX of array when found immediately
return i;
}
}
return -1;
相关文章:
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- Visual Studio Code - C++ Debugger 無法啟動
- Visual Studio Code "undefined reference to `WinMain@16'"
- 当使用通配符和null指针调用函数时,对输出的说明
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 使用VS Code和CMake Tools运行自定义命令
- 修改 VS Code 中的默认C++代码段
- 关于C++中具有多重继承"this"指针的说明
- 16 位到 10 位转换代码说明
- 如何配置Visual Studio Code以使用cygwin,cmake和gcc进行调试
- std::to_string - 'to_string' 不是 'std' 的成员 - Visual Studio Code 1.42.0
- VS Code C++:不准确的系统包括路径错误(wchar.h,boost/lambda/lambda.hpp)
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- C++新手,想知道如何使用VS code 2019播放音频文件
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- 如何在Visual Studio Code中重命名我的a.exe文件?
- C++ Visual Studio Code 的设置不起作用
- 编译器指出结构和 int 说明的错误 2059
- 随机数生成函数说明
- C++ 函数中"Unreachable code"的说明