I am confused in understating the behavior of the code while searching for an element which does not exist in the array.
- The result of the element index i am looking for is always zero while declaring it as
int index;. - The result of the element index i am looking for is random number while declaring it as
size_t index;what is the difference between declaring the variable index asint index;andsize_t;in the code below.
The code
#include <stdio.h>
#define SIZE 5
int main(void)
{
int numbers[SIZE]={1,2,3,4,5};
int search =0; // This variable define the required number i am searching for
int start = 0 ;
int end = SIZE-1 ;
size_t index;
while (start <= end)
{
int middle = (start+end)/2;
if (search == numbers[middle])
{
index = middle;
}
if (search > numbers[middle])
{
start = middle+1 ;
}
else
{
end= middle-1 ;
}
}
printf("The index of the element is %d",index);
return 0;
}
The basic problem is that
indexis not initialized and that it never gets assigned when you don't find what you are searching for. Since theprintfstatement accesses an uninitialized variable in that case, your code have undefined behavior, i.e. anything may happen - including print of all sorts of numbers.That is "just by luck"
That is also "just by luck"