Ada : building with blocks

The term “block of code” is synonymous with a piece of a program nowadays, but some languages do indeed deal more closely with “blocks” – and it’s mostly to do with scope. Ada is one of those languages. A block in Ada allows a new series of variables to be declared whose scope is that block, and any sub blocks within it. Consider this example:

procedure Blocks is
    A : Integer;
    A := 24;
        A : Integer;
        A := 6;

        A, B : Integer;
        A := Blocks.A;     -- A = 24
        B := B12.A;        -- B = 24
    end B12;
    A := 17;

end Blocks;

Ada effectively allows the definition of a procedure which is  executed as inline code. This piece of code is called a block, and is created using three words: declare, begin and end. Within this new space, anything declared in the declaration part between declare and begin can be used in the executable component of the block between begin and end.

So the example above has two blocks within the program. The first does not have a name, and the second one is named B12. Notice that in the main program, and two sub-blocks, the variable A has been declared three times – each one of these has its own scope. The first A is declared in the “main” block, and has a scope which covers the entire program. The next A is declared in the unnamed block and it’s scope is local to that. The final A is declared in the block B12, and is local to that.

Note that in block B12, it is possible to access the A from the main procedure using the dot notation, and  prefixing it with Blocks → Blocks.A (this is really a global variable).  Note also that in B12, A and B12.A denote the same thing. A block is considered a single statement, and there is no limit to the amount of blocks which can be nested.



Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.