goto not always considered harmful (in Ada)

You never thought I would say that did you? But in the right context, goto can be used for good. In languages such as Ada, which has no continue construct for its loops, there are less options. So can a goto be used to build one? The answer is yes. Here is an example:

procedure gotoEG is
  i : integer;
begin
  i := 0;
  while i<5 loop 
    if i rem 2 = 1 then 
        goto Continue; 
    end if; 
    Put(i);
    New_Line;
  <<Continue>> 
    i := i + 1;
  end loop;
end gotoEG;

This works in a very simple way. In the above snippet of code, if i evaluates to an odd integer, control is immediately transferred to the label <<Continue>>, which means the next iteration of the loop is invoked. Why doesn’t Ada have something like a continue (or skip)? Likely because it’s not really a pivotal construct. On a side note, for some reason, it wouldn’t allow the code to appear in the following manner:

  ...
<<Continue>> 
  end loop;
end gotoEG;

When trying to compile this, it threw an Ada “compilation error” because it didn’t like that there was no instruction between the label <<Continue>> and the end of the loop. Is there a way of doing this without using a goto? Yes, but it is a little bit more convoluted. In the code below, an exception is used

procedure nogoto is
  i : integer;
  Continue : exception;
begin
  i := 0;
  while i<5 loop
    i := i + 1;
    Put_Line("start loop");
    begin
      if i rem 2 = 1 then
        raise Continue;
      end if;
      Put(i);
      New_Line;
      exception
        when Continue => null;
    end;
  end loop;
end nogoto;

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s