Constants in Ada

Constants in Ada

Ada supports constants of character, string, boolean, and numeric values.

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;

procedure Constants is
    
    -- Declares a constant value.
    S : constant String := "constant";
    
    procedure Print_String (S : in String) is
    begin
        Put_Line(S);
    end Print_String;
    
begin
    Print_String(S);

    -- A const declaration can appear anywhere a var declaration can.
    N : constant Integer := 500000000;

    -- Constant expressions perform arithmetic with arbitrary precision.
    D : constant Long_Float := 3.0E20 / Long_Float(N);
    Put(D, Exp => 0); New_Line;
    
    -- A numeric constant has no type until it’s given one, such as by an explicit conversion.
    Put(Integer(D)); New_Line;

    -- A number can be given a type by using it in a context that requires one, such as a variable assignment or function call.
    -- For example, here "Ada.Float_IO.Sin" expects a Float.
    Put_Line(Float'Image(Ada.Numerics.Elementary_Functions.Sin(Float(N))));
    
end Constants;

To run the program, compile the code using gnatmake and then execute the compiled binary.

$ gnatmake constants.adb
$ ./constants
constant
6E+11
 600000000000
 -0.284704073237544

Compiling and running Ada programs requires the GNAT compiler, which is part of the GNU Compiler Collection.

Now that we can run and build basic Ada programs, let’s learn more about the language.