Static Variables in Ada


Mark Lundquist demonstrates how to create static variables (variables that maintain their value from one call of the subroutine to the next) in Ada.
    package body Outer is

        package Inner is

            function Foo return Integer;

        end Inner;

        package body Inner is

            V : Integer;        -- V is visible within the body of
                                -- Inner, e.g. to Foo

            function Foo return Integer is
            .
            .
            .
        end Inner;

        function Foo renames Inner.Foo;

    end Outer;

...gives you what you want. Here, Inner exists just to hide V. If you added more things to Inner, they could also see V; this would then be wider visibility than a function static variable.

If you don't care about hiding V to other things in the body of Outer, you can dispense with Inner (and the rename-as-body) altogether:

    package body Outer is

        V : Integer;

        function Foo return Integer is
            .
            .
            .

        end Foo;
    end Outer;

Contributed by: Mark Lundquist
Contributed on: December 4, 1998
License: Public Domain
Back