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

huangapple go评论69阅读模式
英文:

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

问题

当我使用这个函数时,即使数组中有元素,它仍然返回-1。

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

然后我移除了花括号,它就正常工作了。

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

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 &lt; 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 &lt; n; i++) 
        if (arr[i] == target) 
            return i;
    
        return -1;
    
}

答案1

得分: 1

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
英文:

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 &lt; n; i++) {
        if (arr[i] == target){
            return i;}
#else
    for (int i = 0; i &lt; n; i++) {
        if (arr[i] == target) {
            return i;
        }
    }

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

huangapple
  • 本文由 发表于 2023年5月18日 00:27:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274265.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定