Variables in Ada

In Ada, variables are explicitly declared and used by the compiler to ensure type-correctness of operations and function calls.

with Ada.Text_IO; use Ada.Text_IO;

procedure Variables is
   -- Declare a variable
   A : String := "initial";

begin
   -- Print the value of A
   Put_Line(A);

   -- Declare multiple variables at once
   B, C : Integer := 1, 2;
   Put_Line(Integer'Image(B) & " " & Integer'Image(C));

   -- Ada will infer the type of initialized variables
   D : constant Boolean := True;
   Put_Line(Boolean'Image(D));

   -- Variables declared without initialization are default-initialized
   -- For integers, the default value is typically 0
   E : Integer;
   Put_Line(Integer'Image(E));

   -- Ada doesn't have a shorthand declaration and initialization syntax like Go's :=
   -- Instead, we use the full declaration with initialization
   F : constant String := "apple";
   Put_Line(F);
end Variables;

To run this Ada program:

$ gnatmake variables.adb
$ ./variables
initial
 1  2
TRUE
 0
apple

In Ada:

  1. Variables are declared using the name : type := value; syntax.
  2. The constant keyword is used for variables that won’t change after initialization.
  3. Ada doesn’t infer types for variables. You must explicitly declare the type.
  4. Variables are automatically initialized to default values if not explicitly initialized.
  5. Ada doesn’t have a shorthand syntax for variable declaration and initialization like Go’s :=.
  6. To print variables, we often need to convert them to strings using Type'Image(variable).
  7. String concatenation is done with the & operator.

Ada’s strong typing system and explicit declarations help catch errors at compile-time and make the code’s intent clearer.