csyntaxcurly-braceslinear-search

Why curly braces for loop and if give wrong output in linear search in C?


When I used this function, it return -1 even if element of array was there.

int linear_search(int arr[], int length, int target)
{
   
    for (int i=0; i < n; i++) {
        if (arr[i] == target){
            return i;}
    
        return -1;
    }
}

I then removed curly braces and it worked

int linear_search(int arr[], int length, int target)
{
    for (int i=0; i < n; i++) 
        if (arr[i] == target) 
            return i;
    
        return -1;
    
}

Solution

  • The first function would return -1 on the first iteration if arr[i] != target because a return statement follows the if statement inside the loop.

    Aside: I couldn't see the hidden braces at first. Consider adopting one of the following formatting styles:

    #if 0
        for (int i=0; i < n; i++) {
            if (arr[i] == target){
                return i;}
    #else
        for (int i = 0; i < n; i++) {
            if (arr[i] == target) {
                return i;
            }
        }
    
        // Or:
        for (int i = 0; i < n; i++)
        {
            if (arr[i] == target)
            {
                return i;
            }
        }
    #endif