Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a c++ function that returns the index of an array variable. I need explanation on why my part of my code ( ie the 'i++' in the for loop expression) is tagged 'unreachable' by my IDE

I have tried debugging the code line by line to see if i can decipher why the i++ is unreachable. I am unable to identify why. However, I suspect it might have to do with my 'return' statement

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'

like image 763
Oke Avatar asked Dec 05 '22 10:12

Oke


1 Answers

The for loop is not quite right. 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. It never touches the second item in the array.

You need to remove the else part. Return -1 only after the loop ends.

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;
like image 127
R Sahu Avatar answered Dec 21 '22 13:12

R Sahu