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

76 views Asked by At

This is an excerpt from Insertion sort program. Below are given three code fragments, which are different version of same function, and ought to give same output; unfortunately, only the 2nd and 3rd code fragments give the expected output. Why does code fragment 1 act differently?

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;
}
2

There are 2 answers

0
Ami Tavory On BEST ANSWER
  • The first fragment defines the uninitialized variable index_of_smallest_value in the function, sets it for some condition, and returns it. It's good in the sense that it's returning stuff based on function args or local vars, but it has a problem if the condition is never true.

  • The second & third fragment differ from the first in that, if the condition is never true, they return the value of some global variable. They have the opposite strengths & weaknesses from it.


You might consider redesigning the function so that it has both attributes - it relies only on inputs, but it always returns well-defined outputs.

0
Vincenzo Cappello On

index_of_smallest_value in the first case is not initialized, so when the for loop is not executed you have unexoected result.