# Thread: Newb question .. While loop and use of curly brackets on last else in loop

1. ## Newb question .. While loop and use of curly brackets on last else in loop

Hi All,

I'm am new to C and was working on a binary search algorithm.

The last else in the while loop has a statement wrapped in curly brackets and it compiles without errors given. But when i run the code it enters an infinite loop. When i remove the curly brackets it gives no errors and runs fine. I don't understand why it gets stuck in an infinite loop. Why is that? Any C experts maybe wanna explain more about this please?

This is the piece of code:

Code:
```bool search(int value, int values[], int n)
{
int first = 0;
int last = n - 1;
int middle = ( first + last ) / 2;

while ( first <= last )
{
if ( values[middle] == value )
{
return true;
}
else if ( values[middle] < value )
{
first = middle + 1;
}
else
{
last = middle - 1;
middle = ( first + last ) / 2;
} // when removing these bolded brackets the code runs fine
}
return false;
}```
And for those interested in the piece of sorting code the above algorithm is merged with:

Code:
```void sort(int values[], int n)
{
for ( int j = 0; j < n - i - 1; j++)
{
if ( values[j] > values[j+1] )
{
int swap     = values[j];
values[j]    = values[j+1];
values[j+1]  = swap;
}
}
}
return;
}```

2. Well without explicit braces, what you have is
Code:
```        else
{
last = middle - 1;
}

// this happens EVERY time, regardless of if / else logic
middle = ( first + last ) / 2;```

3. Originally Posted by Salem
Well without explicit braces, what you have is
Code:
```        else
{
last = middle - 1;
}

// this happens EVERY time, regardless of if / else logic
middle = ( first + last ) / 2;```
Nice. I see now that's what kept it running.

As for the curly brackets, would you say that the "last = middle - 1;" statement should be in brackets no matter what, even if it does run good without 'm?

4. Originally Posted by moonboots
Nice. I see now that's what kept it running.

As for the curly brackets, would you say that the "last = middle - 1;" statement should be in brackets no matter what, even if it does run good without 'm?
I would suggest you get into the habit of always using them, so you don't have to think too much.
If braces are always present, you won't slip into the trap you fell into - namely adding a line of code completely changed the meaning of the program.