未申明类型的变量默认是初始化变量。
Variables are static by default.
静态变量只会在仿真开始时被初始化为0。即使设计正确,后续调用不会在回到0.
The variable count is a static variable. It will be initialized to zero only once, at the beginning of the simulation. Even if the design
operates correctly, the value of count will eventually exceed the limit of 10 because it is never reset back to zero when the task is
invoked.
function int cnt1(input[3:0] a);
int cnt;
$display("[cnt1], cnt is %0d, a is %d", cnt, a);
cnt += a;
return cnt;
endfunction
initial begin
$display("cnt1 is %0d", cnt1(1));
$display("cnt1 is %0d", cnt1(2));
$display("cnt1 is %0d", cnt1(3));
end
打印结果是
[cnt1], cnt is 0, a is 1
cnt1 is 1
[cnt1], cnt is 1, a is 2
cnt1 is 3
[cnt1], cnt is 3, a is 3
cnt1 is 6
该执行结果不符合预期。实际期望cnt每次调用都会被初始化为0.解决办法:
```c
//方法一:
function int cnt1(input[3:0] a);
int cnt;
cnt = 0; //每次调用都被赋为0
$display("[cnt1], cnt is %0d, a is %d", cnt, a);
cnt += a;
return cnt;
endfunction
//方法二:
function int cnt1(input[3:0] a);
automatic int cnt;//每次调用动态分配空间
$display("[cnt1], cnt is %0d, a is %d", cnt, a);
cnt += a;
return cnt;
endfunction
在循环中同样存在结果不符合预期的情况。
initial begin
int i;
for(i=0; i<5;i++) begin
fork
int id = i;
$display("id is %0d", id);
join_none
end
end
执行结果:
id is 0
id is 0
id is 0
id is 0
id is 0
解决办法只有一种:
initial begin
int i;
for(i=0; i<5;i++) begin
fork
automatic int id = i;
$display("id is %0d", id);
join_none
end
end
执行结果:
id is 0
id is 1
id is 2
id is 3
id is 4
为什么不可以改成?
initial begin
int i;
for(i=0; i<5;i++) begin
fork
int id
id = i;
$display("id is %0d", id);
join_none
end
end
执行结果
id is 5
id is 5
id is 5
id is 5
id is 5
因为该循环中使用的是fork …join_none变量。它会在累加未执行完时退出。所以后续打印结果是cnt累加完的结果。
如果换成fork join,上述打印会符合预期