lundi 24 mai 2021

Error with return keyword inside if statement using C++

#include<iostream>

int searchAnArray(int *arr, int size, int searchKey);

int main()
{
    const int size = 4;
    int array[] = {345,75896,2,543};
    int searchKey = 2;
    std::cout<<"Found at: "<<searchAnArray(array, size, searchKey);
    return 0;
}

int searchAnArray(int *arr, int size, int searchKey){
    int i;
    for(i=0; i<size; i++){
        std::cout<<arr[i]<<" "<<size<<" "<<i<<"\n ";
       if(arr[i] == searchKey){
           return i; break;
        }
        else return -1;
    }

I expect that it should return the index value 2 but unfortunately the value returned is -1.

Can someone explain why?

Aucun commentaire:

Enregistrer un commentaire