17.2.1 Local Declarations Without Block

A basic_declarative_item may appear at the place of any statement. This avoids the heavy syntax of block_statements just to declare something locally.

The only valid kinds of declarations for now are object_declaration, object_renaming_declaration, use_package_clause, and use_type_clause.

For example:

if X > 5 then
   X := X + 1;

   Squared : constant Integer := X**2;

   X := X + Squared;
end if;

It is generally a good practice to declare local variables (or constants) with as short a lifetime as possible. However, introducing a declare block to accomplish this is a relatively heavy syntactic load along with a traditional extra level of indentation. The alternative syntax supported here allows declarations in any statement sequence. The lifetime of such local declarations is until the end of the enclosing construct. The same enclosing construct cannot contain several declarations of the same defining name; however, overriding symbols from higher-level scopes works similarly to the explicit declare block.

If the enclosing construct allows an exception handler (such as an accept statement, begin-except-end block or a subprogram body), declarations that appear at the place of a statement are ‘not’ visible within the handler. Only declarations that precede the beginning of the construct with an exception handler would be visible in this handler.

Attention: Here are a couple of examples illustrating the scoping rules described above.

  1. Those declarations are not visible from the potential exception handler:
    begin
       A : Integer
       ...
    exception
       when others =>
           Put_Line (A'Image) --  ILLEGAL
    end;
    
  2. The following is legal
    declare
       A : Integer := 10;
    begin
       A : Integer := 12;
    end;
    

    because it is roughly expanded into

      declare
         A : Integer := 10;
      begin
         declare
            A : Integer := 12;
         begin
            ...
         end;
      end;
    
    And as such the second ``A`` declaration is hiding the first one.