Title

SystemVerilog -- 3.3 SystemVerilog for loop

SystemVerilog for loop

SystemVerilog中的循环多次重复一组给定的语句,直到不满足给定的表达式。与所有其他过程块一样,循环中需要多个语句被forfor begin end关键字括起来。

Syntax

For循环使用三步方法控制其语句的执行:

  1. 初始化影响循环运行次数的变量
  2. 在执行循环之前,请检查条件是否为真
  3. 修改器在每次迭代结束时执行,并跳转到步骤2
for ([initialization]; <condition>; [modifier])
  // Single statement

for ([initialization]; <condition>; [modifier]) begin
  // Multiple statements
end

Example #1 - Array Iteration

在此示例中,我们将遍历字符串数组并打印出其内容。数组array使用5个不同的水果名称进行初始化。

循环初始化声明一个名为i的局部变量,该变量表示数组中任何元素的索引。条件表达式检查i是否小于数组的大小。修饰符递增i的值,以便循环的每次迭代都对不同的索引进行操作。for

module tb;
  string array[5] = '{"apple", "orange", "pear", "blueberry", "lemon"};

  initial begin
    for (int i = 0; i < $size(array); i++)
      $display ("array[%0d] = %s", i, array[i]);
  end
endmodule

模拟日志

ncsim> run
array[0] = apple
array[1] = orange
array[2] = pear
array[3] = blueberry
array[4] = lemon
ncsim: *W,RNQUIE: Simulation is complete.

Example #2 - Multiple Initializations

在循环的第一部分可以进行多次初始化。在下面显示的代码中,变量ij在输入for循环后立即初始化。为了使示例更有趣,j指向的每个字符串的索引都替换为0。for

module tb;
  string array[5] =' {"apple", "orange", "pear", "blueberry", "lemon"};

  initial begin
    for (int i = 0, j = 2; i < $size(array); i++) begin
      array[i][j] = "0";
      $display ("array[%0d] = %s, %0dth index replaced by 0", i, array[i], j);
    end
  end
endmodule

模拟日志

ncsim> run
array[0] = ap0le, 2th index replaced by 0
array[1] = or0nge, 2th index replaced by 0
array[2] = pe0r, 2th index replaced by 0
array[3] = bl0eberry, 2th index replaced by 0
array[4] = le0on, 2th index replaced by 0
ncsim: *W,RNQUIE: Simulation is complete.

Example #2 - Adding multiple modifiers

在下面显示的代码中,j在循环的每次迭代后都会递减,同时递增ifor

module tb;
  string array[5] =' {"apple", "orange", "pear", "blueberry", "lemon"};

  initial begin
    for (int i = 0, j = array[i].len()-1; i < $size(array); i++, j--) begin
      array[i][j] = "0";
      $display ("array[%0d] = %s, %0dth index replaced by 0", i, array[i], j);
    end
  end
endmodule

模拟日志

ncsim> run
array[0] = appl0, 4th index replaced by 0
array[1] = ora0ge, 3th index replaced by 0
array[2] = pe0r, 2th index replaced by 0
array[3] = b0ueberry, 1th index replaced by 0
array[4] = 0emon, 0th index replaced by 0
ncsim: *W,RNQUIE: Simulation is complete.

posted on   松—松  阅读(308)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

导航

点击右上角即可分享
微信分享提示

目录导航