简体   繁体   English

c ++函数中“无法访问的代码”的说明

[英]Explanation for “Unreachable code” within c++ function

The goal is to write a function that searches an array for a value. 目标是编写一个在数组中搜索值的函数。 If the array contains the value, return the index where the key is located.If the array does not contain the value, return a -1 如果数组包含该值,则返回键所在的索引。如果数组不包含该值,则返回-1

I have a c++ function that returns the index of an array variable. 我有一个c ++函数,它返回一个数组变量的索引。 I need explanation on why my part of my code ( ie the 'i++' in the for loop expression) is tagged 'unreachable' by my IDE 我需要解释为什么我的部分代码(即for循环表达式中的'i ++')被我的IDE标记为'无法访问'

I have tried debugging the code line by line to see if i can decipher why the i++ is unreachable. 我已经尝试逐行调试代码,看看我是否可以破译为什么i ++无法访问。 I am unable to identify why. 我无法确定原因。 However, I suspect it might have to do with my 'return' statement 但是,我怀疑它可能与我的'return'声明有关

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;
            }
        }
    }
}

I expect the function to return the index of the array if a searchKey exists in the array, but it always ends up returning '-1' 如果数组中存在searchKey,我希望函数返回数组的索引,但它总是返回'-1'

The for loop is not quite right. for循环不太正确。 The function returns in the first iteration of the loop regardless of the value of the first item in the array. 无论数组中第一个项的值如何,函数都会在循环的第一次迭代中返回。 If the first item matches the search key, the function returns 1. If not, it returns -1. 如果第一项与搜索键匹配,则函数返回1.如果不匹配,则返回-1。 It never touches the second item in the array. 它永远不会触及数组中的第二项。

You need to remove the else part. 你需要删除else部分。 Return -1 only after the loop ends. 仅在循环结束后返回-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;

Your logic in code decide to return 1 or -1 in the very first time in for loop, so it never touch the i++. 你的代码中的逻辑决定在for循环中第一次返回1或-1,所以它永远不会触及i ++。

You should only return -1 when loop ended (when search done) 你应该只在循环结束时返回-1(搜索完成时)

for(int i=0; i<size; i++){
        if(array[i] == searchkey){
            // return the INDEX of array when found immediately 
            return i;
        }
    }
return -1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM