C++ 函数中"Unreachable code"的说明

Explanation for "Unreachable code" within c++ function

本文关键字:说明 code Unreachable C++ 函数      更新时间:2023-10-16

目标是编写一个在数组中搜索值的函数。如果数组包含该值,则返回键所在的索引。如果数组不包含该值,则返回 -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;