DEV Community

Discussion on: Why switch is better than if-else

Collapse
 
pinotattari profile image
Riccardo Bernardini • Edited

In Ada the corresponding of switch is case. As with many compiled languages, case is limited to discrete type (enumerations or integers). What I like of the Ada case is the absence of C fall-through (potential source of bugs) and the obligation of handling all the cases, possibly with a default branch, that is usually discouraged because it will not catch the error when you add a new enumeration value and forgot to handle it.

One could observe that it is easy to handle all the cases without default when you work with enumerations, but what about integers? Well, you can always define a subtype

  subtype Weekday is integer range 1..7;

  Tomorrow : Weekday;

  case Tomorrow is 
    when 1 => 
    ...
    when 7 =>
  end case;

Finally, if you try to use non-disjoint branches Ada Lovelace herself comes to you and slap your face with the INTERCAL manual. :-)

Oh, BTW, in the latest version of Ada you have also the "operator" version, very convenient and 40 dB more readable than usual "?:"

Name := (case Tomorrow is 
           when 1 => "Monday",
           when 2 => "Tuesday", 
           ...
           when 7 => "Sunday");