systemverilog 静态变量 vs 动态变量

未申明类型的变量默认是初始化变量。

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,上述打印会符合预期

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值