Declaration Blocks
Begin - End
begin
- end
is similar to
{}
- Any
begin-end
block can contain other
begin-end
blocks
-- Demonstrates using a begin-end block.
-- The extra block has no purpose in the program.
procedure anywhere1 is
i: integer := 1;
j: Integer := i;
begin
i := 2 * i;
begin
j := 3 * j;
put(j);
new_line;
end;
end anywhere1;
Begin-end blocks are used for
- Declaration blocks: Like Java declare anywhere
- Exceptions: Like Java
try-catch
Declaration Blocks
-- Demonstrates declaring a variable in a declaration block within a program
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure anywhere2 is
i: integer := 1;
begin
i := 2 * i;
declare
j: Integer := i;
begin
j := 3 * j + i;
put(j);
new_line;
end;
-- put(j); -- Compile error
end anywhere2;
- Variables in a Declare block hide variables with the same name
declared in an enclosing block. Hiding variables is not recommended.
Declare blocks and Dynamic Allocation of Strings
-- Demonstrates declaring a string variable whose size is
-- not known until runtime
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure anywhere3 is
s: String(1..80);
len: integer;
begin
get_line(s, len);
put(s'length);
put(len);
-- How do we output the string that was input?
declare
t: String(1..len) := s(1..len);
begin
put(t);
put(t'length);
end;
end anywhere3;
- We will discuss strings more later.