### 1. Can you return from inside a switch?

binary-search in Exercism question.

```include std/math.e

public function my_find(sequence values, object value)
if length(values) = 0 or value < values[1] or value > values[\$] then
return -1
end if
integer first = 1
integer last = length(values)
while first <= last do
integer middle = ceil((first + last) / 2)
integer comparison = compare(values[middle], value)
switch comparison do
case -1 then
last = middle + 1
case 0 then
return middle
case 1 then
last = middle - 1
end switch
--if comparison = 0 then
--  return middle
--elsif comparison = 1 then -- lower slice
--  last = middle - 1
--else -- upper slice
--  first = middle + 1
--end if
end while
return -1
end function
```

If I do the if, it works. If I do the switch, it fails. Is that because I can't do a return from inside a switch?

The eutest test that fails is

```test_equal("finds a value at the end of a sequence",
7,
my_find({1, 3, 4, 6, 8, 9, 11}, 11))
```

-Bruce

### 2. Re: Can you return from inside a switch?

You've got two "last = " in that switch statement, and zero "first =".

D'oh!

### 4. Re: Can you return from inside a switch?

axtens_bruce said...

Can you return from inside a switch?

To answer this explicitly in case anyone is wondering: yes, you can use return from inside a switch statement.

-Greg

### 5. Re: Can you return from inside a switch?

ghaberek said...

In the same spirit of clarity it is probably also worth mentioning this:

```while some_condition do
switch x do
case a then
break -- [1]
case b then
exit -- [2]
end switch
...
end while
```

Which is perfectly fine on both Euphoria and desktop/Phix, with [1] resuming after the end switch and [2] resuming after the end while.
However, under "with js" (on Phix), since JavaScript uses the "break" keyword for both and has no goto statement, [2] becomes illegal.
It is a limitation of JavaScript, not Phix nor Euphoria, the error message should be pretty clear, just something you should know.
One fix would be to replace the exit with setting a flag and adding a test/exit statement just after the end switch.
A return statement remains perfectly fine in all cases.