第一个代码片段输出与第二个和第三个不同的可能原因是什么?

What will be the possible causes for the 1st code fragment to output differently than 2nd and 3rd?

这是插入排序程序的节选。下面给出了三个代码片段,它们是相同功能的不同版本,应该给出相同的输出;不幸的是,只有第二个和第三个代码片段给出了预期的输出。为什么代码片段 1 的行为不同?

int find_smallest_index(int get_array[],int size,int left_index)    //1st        
{   
    int index_of_smallest_value;
    for(int right_index=left_index+1;right_index<size;right_index++)
      {
        if(get_array[right_index]<get_array[left_index])
        {index_of_smallest_value=right_index;}
      }
    return index_of_smallest_value;
 }


int find_smallest_index(int get_array[],int size,int left_index)   //2nd         
{   

    for(int right_index=left_index+1;right_index<size;right_index++)
    {
        if(get_array[right_index]<get_array[left_index]) 
        {left_index=right_index;}
    }
    return left_index;
}



int find_smallest_index(int get_array[],int size,int left_index)   //3rd           
{   int index_of_smallest_value=left_index;
    for(int right_index=left_index+1;right_index<size;right_index++)
    {
        if(get_array[right_index]<get_array[index_of_smallest_value]) 
        {index_of_smallest_value=right_index;}
    }
    return index_of_smallest_value;
}
  • 第一个片段在函数中定义了未初始化的变量index_of_smallest_value,将它设置为某种条件,然后returns它。从某种意义上说,它是基于函数参数或局部变量的 returning 东西,但如果条件永远不为真,它就会有问题。

  • 第二个和第三个片段与第一个片段的不同之处在于,如果条件永远不为真,它们 return 某个全局变量的值。他们有相反的优点和缺点。


您可以考虑重新设计该函数,使其具有两个属性 - 它仅依赖于输入,但它总是 return 明确定义的输出。

index_of_smallest_value 在第一种情况下没有被初始化,所以当 for 循环没有被执行时你有未执行的结果。