Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ada equivalent of local static variable from C/C++

Tags:

ada

I'm coming from C/C++ on embedded systems and all the time inside a function we use a static variable so that the value is retained throughout calls.

In Ada, it seems like this is only done with the equivalent of file-level static variables. Is there an Ada equivalent.

C++:

function Get_HW_Counter() {
   static int count = 0;
   return ++count;
}

Ada:??

like image 682
Awaken Avatar asked May 05 '13 11:05

Awaken


1 Answers

Package level variables.

Note that packages are not necessarily at file level; you can even create and use a package local to a subprogram if you wish. One use of a package is to create an object and all the methods acting on it (singleton pattern); keeping all details of the object private.

If my understanding of C++ is not too rusty, a close equivalent would be:

package HW_Counter is
   function Get_Next;
private
   count : natural := 0; -- one way of initialising
   -- or integer, allowing -ve counts for compatibility with C++
end HW_Counter;

and that's all the package's customer needs to see.

package body HW_Counter is

   function Get_Next return natural is
   begin
      count := count + 1;
      return count;
   end Get_Next;

begin  -- alternative package initialisation part
   count := 0;
end HW_Counter;

And usage would typically be

   C := HW_Counter.get_next;
like image 176
user_1818839 Avatar answered Sep 19 '22 00:09

user_1818839