Sarathi Salvatore
Sarathi Salvatore

Reputation: 33

Datatype of variable in ada

How can I find the datatype of a variable in Ada?

For example, given

INT : integer;

how can I print "the datatype is integer" for this variable?

In Python, type() can be used to find the type. Is there any similar function in Ada to find the datatype of a variable?

Upvotes: 1

Views: 2925

Answers (2)

Jossi
Jossi

Reputation: 1070

If you declare INT as a Integer, it will always be a Integer in that scope. So you could just make a function like:

function the_type(I : Integer) return String is ("Integer");

I can't think of a reason you would want to check the type of variable INT if it always going to be a Integer.

On the other hand if INT can change type at run-time you will need code to emulate that:

procedure Main is
    type Memory_Type_Enum is (Integer_Type, Float_Type);

    record Variable
        Memory_Location : Address;
        Memory_Type : Memory_Type_Enum;
    end record;

    INT : Variable;
begin
    INT := Allocate_Variable(Float_Type);
    INT := Allocate_Variable(Integer_Type);
    Put_Line(INT.Memory_Type'Img);
end;

But it's up to you how you implement a type check whether you have dynamic type system or static.

Upvotes: 0

ajb
ajb

Reputation: 31689

Ada is a strongly typed language, and when you declare a variable you specify its type. So there is no use for a function to return the variable's type, as there would be in languages with untyped variables. The program already knows the type.

If a variable X is declared with type T'Class, then the type of the actual value can be T or any type derived from T. In that case, you can use X'Tag to get the tag of the value's actual type, which is the closest you can come to getting the actual type. Once you have a tag, you can do things like getting the type's name (there are functions for this in Ada.Tags), comparing it to the tag of some type to see if it's that type, etc. But Integer is not a tagged type, so you can't use 'Tag on it and there would be no use for it.

Upvotes: 5

Related Questions