I write a simple binary search program and meet a problem, see my three confusions below:
-
If I choose
icc -g main.coricc -O0 main.cthe code return wrong answer, but if I useicc -O2 main.cI can have the correct answer. -
When the code
mid = (beg + end) / 2;be defined before theif(beg <= end) {the answer is right no matter what flag I use to compile it. -
I think the problem is the local var
midin the stack during the recursion.
Help me, thank you!
#include <stdio.h>
#define MAX 6
int a[MAX] = {1,2,3,4,5,6};
int improved_binary_search(int key, int beg, int end) {
int mid, temp;
//mid = (beg + end) / 2;
if(beg <= end) {
mid = (beg + end ) /2;
if(a[mid] == key)
return mid;
if(a[mid] < key)
return improved_binary_search(key, mid + 1, end);
if(a[mid] > key)
return improved_binary_search(key, beg, mid - 1);
//printf("test is %d\n", mid);
}
if(mid == 0)
return 0;
if(mid == MAX - 1)
return MAX - 1;
if(a[mid] < key)
return a[mid+1] - key < key - a[mid] ? mid+1 : mid;
if(a[mid] > key)
return a[mid] - key < key - a[mid-1] ? mid : mid-1;
return -1;
}
int main(void)
{
printf("%d\n", improved_binary_search(100, 0, MAX - 1));
return 0;
}
You just declared
midbut did not initialize it, it might happen that if the first if condition(if(beg <= end))is not hit then the value ofmidis Indeterminate.That would result in Undefined Behavior. The behavior you see is because of this UB and not because of compiler configurations.
You should always initialize your variables to meaningful values.