This screencast looks at the use of an automatic variable to allow multiple function calls to each maintain their own storage for the variable. The function is a recursive function to calculate a factorial.
A static variable has its storage allocated when the variable is instantiated, and it is never removed/destroyed.
An automatic variable has its storage allocated when it is used and it is removed/destroyed when the accessing code is exited.
Static vs. Automatic storage Part 2.
In Verilog 1995, storage was static. So, a variable in functions or tasks would exist in a single space in memory, and exist throughout a simulation.
Since Verilog 2001, we can use the 'automatic' keyword (so the stack is used for local variables). Now, variables can be unique for each scope.
See 1800-2012.pdf SystemVerilog LRM Section 6.21 Scope and lifetime
.
SystemVerilog static and automatic variables, with recursive function.
Goal: Calculate 4!=4*3*2*1=24.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| module top;
function int factorial(input int input_int);
int result;
//static int num; //static by default
automatic int num; //static by default
num = input_int;
$display("***factorial() called and num=%0d",num);
if (num>1) begin
result = factorial(num-1) * num;
end else begin
result = 1;
end
return(result);
endfunction
initial begin
$display("\n 4! = %0d", factorial(4));
end
endmodule
// This code is a very modified version of posting:
// https://stackoverflow.com/questions/30973087/what-is-the-benefit-of-automatic-variables
// by Puneet Goel - https://stackoverflow.com/users/2981497/puneet-goel
//Among other changes, variable "int result" was added to provide clarity. Might simply use return variable "factorial" here.
|