Prior to Verilog-2001,
all variables were static, including arguments and return values of tasks and functions. Static variables are allocated and initialized once before time 0, never freed, and can be hierarchically referenced. Automatic variables are allocated and initialized each time a particular scope is activated (executed), and the variable disappears when the scope is deactivated.
If you have the function
Code:
function reg [31:0] count_ones(input reg [31:0] value);
integer i;
reg [5:0] total1 = 0;
begin
for ( i=0; i<32; i=i+1) total1 = total + value[i];
count_ones = total1;
end
endfunction
This works the first time you call count_ones() because total1 is 0 to start with. And it will continue to work until you call it after total1 is not zero. Then it will add it to the previous count.
As a pure hardware description language, the thought was that hardware was only static; you can't add hardware once the design starts. However, for testbenches and for synthesizable code that is more software-like, Verilog-2001 added the ability to declare functions and tasks as automatic, so that all its arguments and the variables declared inside it are allocated and initialized each time the task or function is called. So if you change the header of the function to
Code:
function automatic reg [31:0] count_ones(input reg [31:0] value);
integer i;
reg [5:0] total1 = 0;
begin
for ( i=0; i<32; i=i+1) total1 = total + value[i];
count_ones = total1;
end
endfunction
now total1 is an automatic variable and will be initialized each time the function is called.
The benefit of automatic variables is even more visible when you have a recursive function, or concurrently active tasks and each active task/function needs an independent copy of its variables instead of sharing a global static variable.
Code:
function automatic int factorial(int n);
if (n==0)
return 1;
else
return factorial(n-1) *n;
endfunction
This would not work if n was a static variable because each call to factorial(n-1) would change the value of n in the current scope.
SystemVerilog adds the ability to declare individual variables as either static or automatic and made the first example I gave illegal. Too many people are familiar with most other programming languages where automatic variables are the default. They do not realize the initialization happens only once at time 0. So SV makes you use the 'static' keyword explicitly if that is what you really want, or code it so it does the initialization each time the scope is entered.