I tied to write binary search code in Recursive. and I first wite this:
int rSearch(int numbers[],int start, int end, int x){ int mid; if(start <= end){ mid = (start + end)/2; if(numbers[mid] == x) return mid; else if(numbers[mid] > x) rSearch2(numbers, start, mid-1, x); else rSearch2(numbers, mid+1, end, x); } else return -1; } and it's work perfect. but after i searched about it I understand I have to write code like this:
int rSearch2(int numbers[],int start, int end, int x){ int mid; if(start <= end){ mid = (start + end)/2; if(numbers[mid] == x) return mid; else if(numbers[mid] > x) return rSearch2(numbers, start, mid-1, x); else return rSearch2(numbers, mid+1, end, x); } else return -1; } because in first code we may not have return value.
my question is why first code worked?
}that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined." 6.9.1p12