Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ada Case Statement behave like in C?

Tags:

case

break

ada

when you use Ada case statements each case has automatically a break. In C (or other languages) this break is not automatically done and all cases after the true one are executed. Is it possible also to have this behaviour in Ada or a workaround?

like image 635
Rainflow Avatar asked Dec 10 '16 12:12

Rainflow


2 Answers

There will never be behaviour like this in Ada!

The only reasonable workround would be to take the repeated section of code, put it in a (local) procedure, and call it where required.

The reason Ada’s case statement is like this is that the C style makes it all too easy to forget the break (adding /* FALLTHROUGH */ comments for a deliberate omission doesn’t really make the code easier to read - is an uncommented omission a mistake? how much surrounding code would you need to read to be sure?).

In MISRA C (here, for example) rule 15.2 near the bottom of page 60 says

An unconditional break statement shall terminate every non-empty switch clause.

and Ada, being intended for a similar market, has taken the same position.

Most times, multiple alternatives for one action is all that’s needed:

case K is
   when 1 | 5 | 10 .. 20 =>
      Action_1;
   when 3 =>
      Action_2;
   ...
end case;
like image 152
Simon Wright Avatar answered Sep 28 '22 19:09

Simon Wright


Of course you can. But it's such a rarely needed behaviour that there's no specific syntax providing it, so you just have to roll it yourself using low level primitives.

One approach is to use labels and gotos, with the case decision logic cleanly separated from the statement logic as here..

with Ada.Text_IO; use Ada.Text_IO;

procedure c_case_example is

c_case : natural range 1 .. 10 := 1;

begin

   case c_case is
   when 1       => goto case_1;
   when 3 .. 5  => goto case_3;
   when 6|8     => goto case_6;
   when others  => goto case_others;
   end case;

   <<case_1>>      put_line("Case 1");
   <<case_3>>      put_line("Case 3,4,5");
                   goto break;
   <<case_6>>      put_line("Case 6,8");
   <<case_others>> put_line("all other cases");
   <<break>>       null;

   put_line("Done");

end c_case_example;

Yes it's ugly. If you want to program C in Ada, it's going to be ugly.

like image 23
user_1818839 Avatar answered Sep 28 '22 19:09

user_1818839