tags:

views:

96

answers:

4

Below is a piece of code shown and doubts are regarding the implementation of loops

               C := character'last; --'// SO code colorizer hack
               I := 1;
               K : loop
                  Done := C = character'first; --'
                  Count2 := I;
                  Exit K when Done;
                  C := character'pred(c);  --'
                  I := I + 1;
               end loop K;

Can anyone please tell me what does 'K' stands for.I guess its not a variable.How does 'K' control the execution of the loop?

+3  A: 

K is the name of the loop. The end loop and Exit statements refer to that name, to make it clear what loop is being exited.

The Ada Reference Manual calls it a "loop_statement_identifier".

David Gelhar
+1  A: 

K is a label that names the loop. Wow, it has been a long time since I've seen any Ada...

+2  A: 

As noted, K is the loop's label. It allows you to identify a particular loop to aid readability, and also to selectively exit a specific loop from a set of nested enclosing ones (i.e. being a "goto"...shhh! :-)

Here's a contrived example (not compiled checked):

   S : Unbounded_String;
   F : File_Type;
   Done_With_Line : Boolean := False;
   All_Done       : Boolean := False;
begin
    Open(F, In_File, "data_file.dat");
  File_Processor:
    while not End_Of_File(F) loop
        S := Get_Line(F);
       Data_Processor:
        for I in 1 .. Length(S) loop
           Process_A_Character
                (Data_Char => Element(S, I),   -- Mode in
                 Line_Done => Done_With_Line,  -- Mode out
                 Finished  => All_Done);       -- Mode out

           -- If completely done, leave the outermost (file processing) loop
           exit File_Processor when All_Done;

           -- If just done with this line of data, go on to the next one.
           exit Data_Processor when Done_With_Line;
        end loop;
    end loop File_Processor;
    Close(F);
 end;
Marc C
Bah. Don't scare beginners off with the dreaded "g-word". `exit` is no more of a goto than `if`, `loop`, and `case` are.
T.E.D.
+2  A: 

K is essentially the name of the loop. The exit k tells the code to stop looping and go to the next statement after loop k ends.

You usually don't need to name loops, as you can just say exit and it will exit the enclosing loop. However, if you have a loop nested inside another loop, and you'd like to exit not the one immediately around the exit statement, but the outermost one, then doing something like this may be required.

T.E.D.