Specific behaviour of {if else} in C

258 Views Asked by At

I have a functioning binary array search algorithm, here it is:

int binarySearch(int array[],int n,int elem){

    int high =n-1;  
    int low = 0;
    int mid;
    while(low<=high)
    {
        mid=(low+high)/2;
        if(elem>array[mid]){
            low=mid+1;
        }
        else if(elem<array[mid]){
            high=mid-1; 
        }
        else return mid;
    }   
    return -1;
}

but now I want to know the amount of comparisons made between elements of the array, I know how to do that, but my questions are:

When the compiler finds one of the clauses to be true, does it still go into the other clauses? example: when elem>array[mid] it makes one comparison, so now he should know that the following else if is false, but does it still make the comparison?

And what about the else? when he found the if and else if to be false, does he secretly make a comparison (elem==array[mid])?

4

There are 4 best solutions below

3
On

when elem>array[mid] it makes one comparison, so now he should know that the following "else if" is false, but does it still make the comparison?

No. If the first if statement is true, then the following if else and else clauses won't be executed.

And what about the "else"? when he found the "if" and "else if" to be false, does he secretly make a comparison (elem==array[mid])?

No. The final else will be executed unconditionally in this case. No secret comparsion will be made.

0
On
if(cond) ..
else if (condn)..
else ...

So just to put it simply when if condition passes else if and else conditions are ignored only when if is false elseif is checked and when if and elseif both are false else will be executed without considering conditions internally.

0
On

The compiler keeps on checking from the start of a if - else if clause.If any one condition is true it skips all the other else ifs and else comparisons.However when you work with if-if clause it checks all possible conditions and excecutes accordingly.

0
On

if-else structures can sometimes be hard to follow. When you see something like:

if(elem>array[mid]){
        low=mid+1;
    }
    else if(elem<array[mid]){
        high=mid-1; 
    }
    else return mid;

it may help to notice that the if-else pairs are nested. It's easier to see with some parentheses. Take for example one if-else statement pair:

if(condition)
    { something;
    }
else(condition)
    { something;
    }

If the if condition is satisfied, the else portion will not be executed.

Applying this principle: This can be extended to your code. It could functionally be rewritten as:

if(elem>array[mid])
     {
        low=mid+1;
     }
else {
       if(elem<array[mid])
      {
       high=mid-1; 
      }
       else
          return mid;
    }

As you can see, the second if-else pair is nested within the first else statement. This way, if the first if condition is true, nothing else will be executed.

I hope this helps.