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:??
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With