views:

421

answers:

1

I'm coming from Java/C++ to Ada and am having trouble figuring out the small stuff. Is it possible to declare an array and ask the user for the min/max values then initialize it? I don't like having to define constant values for the MIN and MAX and it seems like there should be a way to do this.

You can define an unconstrained type, but you still have to initialize the size in the declare block before your program starts. Would I need to have the package body, then the procedure declaration, then a declare block inside the procedure that actually does the work, like the following?

PACKAGE BODY Build_Graph IS
    TYPE Graph_Box IS ARRAY(Integer RANGE <>, Integer RANGE <>) of Character;

    PROCEDURE Print_Graph(Min, Max, Height, Width: IN Integer) IS
    BEGIN
        DECLARE
            Graph: Graph_Box(0..Height, 0..Width);
        BEGIN
            Do_Stuf(Graph);
        END;
    END Print_Graph;

END Build_Graph;
+2  A: 

What you show there should work. However, the "declare" block is totally unnessecary, unless you want to catch range exceptions on the array variable declaration or something. I'd change it to read:

procedure Print_Graph(Min, Max, Height, Width: in Integer) is
    Graph: Graph_Box(0..Height, 0..Width);
begin
    Do_Stuf(Graph);
end Print_Graph;

(I also dislike having the reserved words in caps.)


One further thing I should mention: Ada arrays don't have to be 0-based like in cish languages. They can be, but you can also make them start at 1, or -200, or whatever you want.

The reason I bring this up is that I see the way you defined Graph_Box it is actually Height+1 elements high and Width+1 elements wide. You probably don't want that, as it is liable to confuse somebody later (perhaps even you).

My typical idiom is to start my array indices at 1, unless I have some good reason not to.

T.E.D.